Is there a way to search the DOM for an element with a particular stylename class? Something like:
var node = document.findByClassName("foo");
if so, will this be extremely slow if my page has like 2000 elements in it or so?
Thanks
Well, jQuery has a class selector:
$('.foo')
You can look there for an implementation.
Firefox supports a native getElementsByClassName()
AFAIK.
If the browser does not support the native method you can sift through every tag and look for the class names. This version allows you to specify a parent to search from and more than one class can be matched. It returns an array of nodes in either case, not a 'live' nodelist.
function getbyClass(classes, pa){
pa= pa && pa.nodeType== 1? pa: document;
// native support:
if(pa.getElementsByClassName){
var A= [], N= pa.getElementsByClassName(classes);
for(var i= 0, L= N.length; i<L; i++){
A[i]= N[i];
}
return A;
}
// no native support:
var elems= [], c= classes.split(/ +/), L= c.length, tem, temc,
tags= pa.getElementsByTagName('*'), max= tags.length;
for(var i= 0, L= c.length; i< L; i++){
c[i]= RegExp('\\b'+c[i]+'\\b');
}
getbyClassloop:
while(max){
i= L;
tem= tags[--max];
temc= tem.className;
if(temc){
while(i){
if(!c[--i].test(temc)) continue getbyClassloop;
}
elems[elems.length]= tem;
}
}
return elems;
}
// use-
getbyClass('classname')
// searches document for elements with classname
getbyClass('classname1 classname2')
// searches document for elements with both classes
getbyClass('classname1 classname2',containingelement)
// searches only containingelement and descendents
/*IE9 will have support for the native method, and versions of IE below 8, as well as some other older browsers, will fall back to the sifting method. You can add a quicker method than the sifter to IE8. */
(function(){
if(!document.getElementsByClassName && document.attachEvent){
try{
if(document.querySelectorAll){
var IE8class= function(classes){
var C= classes.split(' '), tem,
els= Array.from(this.querySelectorAll('.'+ C.shift()));
while(C.length && els.length){
tem= C.shift();
els= els.testEach(function(itm){
return itm.className.indexOf(tem)!= -1;
});
}
return els;
}
HTMLDocument.prototype.getElementsByClassName= IE8class;
Element.prototype.getElementsByClassName= IE8class;
return true;
}
}
catch(er){
return false
};
}
})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With