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:
-
if(document.getElementsByAttribute == undefined) {
-
document.getElementsByAttribute = function(attribute, parentElement) {
-
var _selectedElements = new Array();
-
var _allElements = document.body.getElementsByTagName('*');
-
dojo.lang.forEach(_allElements,
-
function(node) { //have to use getAttributeNode since it's the only one supported by all browsers
-
if (node.getAttributeNode(attribute) != undefined) {
-
_selectedElements.push(node);
-
}
-
}, true);
-
return _selectedElements;
-
}
-
-
}
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.


