getElementsByAttribute

I wanted to extend getElementsByAttribute to search a spe­cific attrib­ute and whilst some getElementsByAttribute func­tions 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, optim­ise. That’s why there’s a switch state­ment 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 res­ult from getElementsByAttribute was an array but you may want to change this. If you have a getElementsByClassName func­tion, you could also incor­por­ate it into the switch statement.

Very simply, it runs through an array of all the child ele­ments and adds it to an array if it matches the cri­teria. 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.

    What do you think? Leave a comment...