77

What is the best method to retrieve an array of elements that have a certain class?

I would use document.getElementsByClassName but IE does not support it.

So I tried Jonathan Snook's solution:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = document.getElementsByClassName(document.body,'tab');

...but IE still says:

Object doesn't support this property or method

Any ideas, better methods, bug fixes?

I would prefer not to use any solutions involving jQuery or other "bulky javascript".

Update:

I got it to work!

As @joe mentioned the function is not a method of document.

So the working code would look like this:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}
var tabs = getElementsByClassName(document.body,'tab');


...Also if you only need IE8+ support then this will work:

if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
        return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}

Use it just like normal:

var tabs = document.getElementsByClassName('tab');
Community
  • 1
  • 1
Web_Designer
  • 72,308
  • 93
  • 206
  • 262
  • 2
    Are you sure your update is right? Shouldn't it be var tabs = getElementsByClassName(document.body,'tab'); **notice I removed document.getEle... ** – Anthony Dec 23 '12 at 18:01
  • Are your last examples correct? You are passing in '.tab' but shouldn't it be without the period since your inner method adds the period and if it is IE9+ then it doesn't have the period either? Shouldn't it be var tabs = document.getElementsByClassName('tab');? And why do you have an "or" when the last two examples are the same? I must be missing something. – BoBoCoding Apr 21 '16 at 00:55
  • @BoBoCoding fixed. – Web_Designer Apr 22 '16 at 10:55
  • See also `getElementsByClassName` polyfill [gist](https://gist.github.com/eikes/2299607) in [Polyfill for getElementsByClassName for particular uses](https://stackoverflow.com/questions/18944659/polyfill-for-getelementsbyclassname-for-particular-uses). – Vadzim Apr 02 '19 at 09:58
  • @Web_Designer -- If my prior comment was helpful, can I get an up-vote on it? Since "reputation" does open up different features on stack-overflow. Thanks. – BoBoCoding Mar 28 '22 at 23:45

7 Answers7

56

It's not a method of document:

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

tabs = getElementsByClassName(document.body,'tab');  // no document
Joe
  • 80,724
  • 18
  • 127
  • 145
18

you may create the function for older browsers

if (typeof document.getElementsByClassName!='function') {
    document.getElementsByClassName = function() {
        var elms = document.getElementsByTagName('*');
        var ei = new Array();
        for (i=0;i<elms.length;i++) {
            if (elms[i].getAttribute('class')) {
                ecl = elms[i].getAttribute('class').split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            } else if (elms[i].className) {
                ecl = elms[i].className.split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            }
        }
        return ei;
    }
}
gdarcan
  • 595
  • 5
  • 8
14
function getElementsByClassName(className) {
if (document.getElementsByClassName) { 
  return document.getElementsByClassName(className); }
else { return document.querySelectorAll('.' + className); } }

Pretty sure this is the same as Leonid's function but this uses document.getElementsByClassName when it can.

Mike_OBrien
  • 1,395
  • 15
  • 34
10

You can't really replicate getElementsByClassName, because it returns a nodeList, and so its value is live, and updates with the document.

You can return a static Array of elements who share the same classnames- but it won't 'know'when the document changes.

(It won't take too many of these kind of things to make a library look svelte...)

function getArrayByClassNames(classes, pa){
    if(!pa) pa= document;
    var C= [], G;
    if(pa.getElementsByClassName){
        G= pa.getElementsByClassName(classes);
        for(var i= 0, L= G.length; i<L; i++){
            C[i]= G[i];
        }
    }
    else{
        classes= classes.split(/\s+/);
        var who, cL= classes.length,
        cn, G= pa.getElementsByTagName('*'), L= G.length;
        for(var i= 0; i<cL; i++){
            classes[i]= RegExp('\\b'+classes[i]+'\\b');
        }
        classnameLoop:
        while(L){
            who= G[--L];
            cn= who.className;
            if(cn){
                for(var i= 0; i<cL; i++){
                    if(classes[i].test(cn)== false) {
                        continue classnameLoop;
                    }
                }
                C.push(who);
            }
        }
    }
    return C;
}

//Example

var A= getArrayByClassNames('sideBar local')

kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 3
    +1 for noting that unlike the real `getElementsByClassName`, the compatibility hacks (including `querySelectorAll`) provide static snapshots, not live collections. – Søren Løvborg Oct 23 '13 at 08:58
9

IE8:

document.getElementsByClassName = function (className) {
    return document.querySelectorAll('.' + className)
}
Leonid
  • 3,121
  • 24
  • 31
  • 1
    Doesn't work on my IE9: "Object doesn't support property or method 'querySelectorAll'" – Phil Sep 10 '12 at 19:04
0

I just want to improve querySelectorAll fallback for IE8.

Like others answered, the simple way is adding the function to Element.prototype with

this.querySelectorAll('.' + className);

But there are some problems:

  • It doesn't work with untrimmed strings (at the beginning).
  • It doesn't work with multiple classes.
  • It doesn't work with "strange" class characters (/, $, *, etc.)
  • It doesn't work with classes which begin with a digit (invalid identifiers)

That means there should be some "fixing", for example:

"abcd"     ->  ".abcd"
"a   b cd" ->  ".a.b.cd"
"   a b  " ->  ".a.b  "
"a/b$c d"  ->  ".a\/b\$c.d"
"1234"     ->  ".\000031234"

Code:

this.querySelectorAll(className
    .replace(/(?=[^ \w])/g, '\\')   // Escape non-word characters
    .replace(/\b\d/g, '\\00003$&')  // Escape digits at the beginning
    .replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces
);
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    The function can also be added to `HTMLDocument.prototype` in order to use it with `document`. – Oriol Feb 15 '14 at 02:11
0
function _getClass(whatEverClasNameYouWant){
var a=document.getElementsByTagName('*');
   for(b in a){
      if((' '+a[b].className+' ').indexOf(' '+whatEverClasNameYouWant+' ')>-1){
      return a[b];
      }
   }
}