Posted By


erintechspired on 02/12/10

Tagged


Statistics


Viewed 517 times
Favorited by 0 user(s)

getElementBySimilarId


/ Published in: JavaScript
Save to your folder(s)

A simple, non-recursive function that I use to return the first element with an ID that contains a certain ID string.
Sometimes, APS.NET appends the Naming Container ID to the IDs of controls, and in instances where the ClientID of a control you want is not available, you can use this script to find the element you want by similar id.
Dirty, but works most of the time for me.


Copy this code and paste it in your HTML
  1. //-----------------------------------------------------------------
  2. //Usage: Returns the first instance of a DOM Element that contains the
  3. // desiredElementId. Useful if your framework appends to IDs, instead of
  4. // IE: myElement, you have ct001_myElement
  5. //Parameters:
  6. // desiredElementId - The id to search for
  7. // tagName - (Optional) The tag name of elements to get.
  8. // (If you know your element is a div, for example, search only divs.)
  9. //-----------------------------------------------------------------
  10. function getElementBySimilarId(desiredElementId, tagName) {
  11. var elems;
  12. var returnElem = null;
  13. //Get all elements of the correct type
  14. if (tagName == null || tagName == '') {
  15. elems = document.getElementsByTagName('*');
  16. }
  17. else {
  18. try {
  19. elems = document.getElementsByTagName(tagName);
  20. }
  21. catch (e) {
  22. alert(type + ' is not a valid tagName/Element Type');
  23. }
  24. }
  25. //iterate through the elements
  26. for (var i = 0; i < elems.length; i++) {
  27. if (elems[i].id.indexOf(desiredElementId) > -1) {
  28. returnElem = elems[i];
  29. break;
  30. }
  31. }
  32. return returnElem;
  33. }

URL: http://techspired.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.