If the browser does not support its own method, you can sift through each tag and look for class names. This version allows you to specify the parent to search, and more than one class can be mapped. It returns an array of nodes anyway, 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 support its own method, and versions of IE below 8, as well as some other older browsers, will return to the screening method. You can add a faster method than a filter in 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 }; } })()
source share