Monday code giveaway: getElementsByAttribute
Updated September 27th 2006
Apparently Opera’s claim to support document.all in conjunction with not mimicking it exactly like IE led to some problems in Opera 9. Thanks to Ash Searle who tipped me about this and also explained what the problem was. The code below and the JavaScript file to download are updated.
Since we all have to face a new hard tough week now, I thought I’d brighten your day by giving you some code that might be useful.
Ever run into a situation where you want to get an array of all elements with a specific attribute? Or even want elements with a certain value for that chosen attribute, as well? That’s not a problem anymore; let me present getElementsByAttribute.
/*
Copyright Robert Nyman, http://www.robertnyman.com
Free to use if this text is included
*/
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
var oCurrent;
var oAttribute;
for(var i=0; i<arrElements.length; i++){
oCurrent = arrElements[i];
oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
if(typeof oAttribute == "string" && oAttribute.length > 0){
if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
arrReturnElements.push(oCurrent);
}
}
}
return arrReturnElements;
}
The parameters are:
- oElm
- Mandatory. This is element in whose children you will look for the attribute.
- strTagName
- Mandatory. This is the name of the HTML elements you want to look in. Use wildcard (
*) if you want to look in all elements. - strAttributeName
- Mandatory. The name of the attribute you’re looking for.
- strAttributeValue
- Optional. If you want the attribute you’re looking for to have a certain value as well.
And these are a couple of examples how it can be called:
getElementsByAttribute(document.body, "*", "id");
getElementsByAttribute(document.getElementById("the-form"), "input", "type", "text");
Web browser compatibility
The code has been tested and verified to work in:
- All Firefox versions, all the way back to Firebird (remember that one? :-))
- IE 5.0+, PC
- IE 5.2, Mac
- Safari 1.3
- Opera 7.03
To use it, just copy and paste above code or download the getElementsByAttribute.js file.






