GetElementsByAttribute

Sep 23, 2003

Could be rewritten to work in ie5w, ie5m, of course, but I like it like it is:

// document.getElementsByAttribute([string attributeName],[string attributeValue],[boolean isCommaHyphenOrSpaceSeparatedList:false])
document.getElementsByAttribute=function(attrN,attrV,multi){
attrV=attrV.replace(/|/g,'|').replace(/[/g,'[').replace(/(/g,'(').replace(/+/g,'+').replace(/./g,'.').replace(/*/g,'*').replace(/?/g,'?').replace(///g,'/');
var
multi=typeof multi!='undefined'?
multi:
false,
cIterate=document.getElementsByTagName('*'),
aResponse=[],
attr,
re=new RegExp(multi?''+attrV+'':'^'+attrV+'$'),
i=0,
elm;
while((elm=cIterate.item(i++))){
attr=elm.getAttributeNode(attrN);
if(attr &&
attr.specified &&
re.test(attr.value)
)
aResponse.push(elm);
}
return aResponse;
}

View 17 Replies


ADVERTISEMENT

GetElementsByAttribute() For Prototype

Apr 9, 2006

This function will return an array of the elements in a page that contain a certain attribute, you can also give it a value that the attribute has to match, a tag name that the element has to match and a parent element.

I know there are other functions for doing this, but this one is written for use with the prototype (http://prototype.conio.net/) JavaScript library, in fact its really just a modified version of the getElementsByClassName() function that’s part of prototype.

document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
return $A(children).inject([], function(elements, child) {
var attributeValue = child.getAttribute(attribute);
if(attributeValue != null) {
if(!value || attributeValue == value) {
elements.push(child);
}
}
return elements;
});
}

Usage is pretty simple, this will return all elements with a width attribute:

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved