Lazycoder

29Mar/060

Grabbing arbitrary elements from the DOM

In the Javascript library I'm working on, I needed to be able to grab all of the elements in the page DOM that had a certain attribute. There isn't any way through the DOM to currently do this. So I came up with this little function. It appears to be working, but I haven't tested it with a very complicated page yet. The library is based on the Dojo toolset, so I'm leveraging some of it's built in methods like forEach. Right now it just returns a standard Javascript array like the other dom get* methods, but that may change to a hashtable at some point.

JAVASCRIPT:
  1. if(document.getElementsByAttribute == undefined) {
  2.     document.getElementsByAttribute = function(attribute, parentElement) {
  3.         var _selectedElements = new Array();
  4.         var _allElements = document.body.getElementsByTagName('*');
  5.         dojo.lang.forEach(_allElements,
  6.                 function(node) { //have to use getAttributeNode since it's the only one supported by all browsers
  7.                                 if (node.getAttributeNode(attribute) != undefined) {
  8.                                       _selectedElements.push(node);
  9.                                     }
  10.                 }, true);
  11.         return _selectedElements;
  12.         }
  13.              
  14. }

n.b. There's a bug in the code. It doesn't actually use the parentElement if it's provided. It's pretty trivial to make it work. Eventually I'll update this code with the fixed code.