I wanted to extend getElementsByAttribute to search a specific attribute and whilst some getElementsByAttribute functions exist, none of them feel that fantastic.
Object.prototype.getElementsByAttribute = document.getElementsByAttribute = document.getElementsByAttribute || function(attribute, value) {
switch(attribute) {
case 'id':
return [this.getElementById(value)];
case 'tagName':
return this.getElementsByTagName(value);
}
for(var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = []; i < elementsLength; i++)
{
if(elements[i][attribute] == value)
{
b.push(elements[i]);
}
}
return b;
};
First of all, if you can, optimise. That’s why there’s a switch statement that checks for "tagName" and "id" in the cases that you would want to use getElementsByTagName or getElementById. I made the getElementById return in an array so every result from getElementsByAttribute was an array but you may want to change this. If you have a getElementsByClassName function, you could also incorporate it into the switch statement.
Very simply, it runs through an array of all the child elements and adds it to an array if it matches the criteria. That array is then returned.
And because of how it is designed, you can call it with any DOM element:
document.getElementsByAttribute('title', 'Document Object Model');
var content = document.getElementById('content);
content.getElementsByAttribute('title', 'Document Object Model');
Comments
No responses have been made so far. Add your comments.