getElementsByClassName() doesn't work in old Internet Explorers like IE6, IE7, IE8
L

5

17

The following code:

var borderTds = document.getElementsByClassName('leftborder');

gives me an error message in Internet Explorer 6, 7 and 8:

Object does not support this method

How can I select elements by their class in these browsers?

I prefer not to use JQuery.

Licentiate answered 5/7, 2011 at 14:49 Comment(4)
possible duplicate of getElementsByClassName & IEMannes
I think jQuery supports such functionality.Bivalve
An alternative to using jQuery would be to just use the Sizzle selector engine. But if all you need is to select by class, then I'd just write a replacement.Manzanilla
@ChaosPandion: "I prefer not to use JQuery".Mannes
L
13

This solution may help. This is a custom getElementsByClassName function implemented in pure javascript, that works in IE.

Essentially what this script is doing is probing, one by one, all possible options and picks the best one available. These options are:

  1. Native document.getElementsByClassName function.
  2. document.evaluate function, which allows evaluation of XPath queries.
  3. Traversing the DOM tree.

Of course the first one is the best performance-wise, however the latter should be available everywhere including IE 6.

Usage example, which is also available on the page, looks like this:

getElementsByClassName("col", "div", document.getElementById("container")); 

So the function allows 3 parameters: class (required), tag name (optional, searches for all tags if not specified), root element (optional, document if not specified).

Update. The solution linked in the blog post is hosted on the Google Code which is shutting down in Jan 2016. However the author has made it available on GitHub. Kudos to flodin pointing this out in the comments.

Logia answered 5/7, 2011 at 14:53 Comment(4)
-1 for just posting a link. As per the FAQ "Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."Marc
@codemonkeh, can't but agree, so let's improve it! Updated the post. Does this look better?Logia
Note for future visitors: the linked solution is hosted on Google Code which is being shut down, but the original author has moved it to GitHub.Vikkivikky
@flodin, thanks for cathing this, updated the post for better visibility.Logia
N
16

IE6, Netscape 6+, Firefox, and Opera 7+ copy the following script in your page:

document.getElementsByClassName = function(cl) {
  var retnode = [];
  var elem = this.getElementsByTagName('*');
  for (var i = 0; i < elem.length; i++) {
    if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]);
  }
  return retnode;
}; 
Nonprofessional answered 5/7, 2011 at 14:52 Comment(2)
Actually, using \b can lead to problems with classes containing -. Better add spaces: if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1).... That's the method jQuery uses.Mannes
I am stuck working in IE6. Seems IE6 doesn't have .indexOf() as your code shows. I had to make a brief replacement function: function indexOf(Arr, Match) { var Result = -1; var i; for (i=0; i < Arr.length; i++) { if (Arr[i] != Match) continue; Result = i; break; } return Result; }Conative
L
13

This solution may help. This is a custom getElementsByClassName function implemented in pure javascript, that works in IE.

Essentially what this script is doing is probing, one by one, all possible options and picks the best one available. These options are:

  1. Native document.getElementsByClassName function.
  2. document.evaluate function, which allows evaluation of XPath queries.
  3. Traversing the DOM tree.

Of course the first one is the best performance-wise, however the latter should be available everywhere including IE 6.

Usage example, which is also available on the page, looks like this:

getElementsByClassName("col", "div", document.getElementById("container")); 

So the function allows 3 parameters: class (required), tag name (optional, searches for all tags if not specified), root element (optional, document if not specified).

Update. The solution linked in the blog post is hosted on the Google Code which is shutting down in Jan 2016. However the author has made it available on GitHub. Kudos to flodin pointing this out in the comments.

Logia answered 5/7, 2011 at 14:53 Comment(4)
-1 for just posting a link. As per the FAQ "Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."Marc
@codemonkeh, can't but agree, so let's improve it! Updated the post. Does this look better?Logia
Note for future visitors: the linked solution is hosted on Google Code which is being shut down, but the original author has moved it to GitHub.Vikkivikky
@flodin, thanks for cathing this, updated the post for better visibility.Logia
I
7

Internet Explorer 8 and older does not support getElementsByClassName(). If you only need a solution for IE8, it supports querySelectorAll(), you can use one of these instead. For older IEs you have to provide your own implementation, and for some other ancient browsers that support it you can also use evaluate() which runs XPath expressions.

This code provides a document.getElementsByClassName method if it does not exist yet using the methods I've described:

if (!document.getElementsByClassName) {
  document.getElementsByClassName = function(search) {
    var d = document, elements, pattern, i, results = [];
    if (d.querySelectorAll) { // IE8
      return d.querySelectorAll("." + search);
    }
    if (d.evaluate) { // IE6, IE7
      pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
      elements = d.evaluate(pattern, d, null, 0, null);
      while ((i = elements.iterateNext())) {
        results.push(i);
      }
    } else {
      elements = d.getElementsByTagName("*");
      pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
      for (i = 0; i < elements.length; i++) {
        if ( pattern.test(elements[i].className) ) {
          results.push(elements[i]);
        }
      }
    }
    return results;
  }
}

If you don't like something about it, you can use your favorite search engine to find a different one.

Intrust answered 31/7, 2014 at 8:43 Comment(0)
E
6

The method doesn't exist in IE6. If you want to select elements by class and don't want to use a library, you simply have to loop through all elements in the page and check for the class in their className property.

function getElementsByClassName(className) {
  var found = [];
  var elements = document.getElementsByTagName("*");
  for (var i = 0; i < elements.length; i++) {
    var names = elements[i].className.split(' ');
    for (var j = 0; j < names.length; j++) {
      if (names[j] == className) found.push(elements[i]);
    }
  }
  return found;
}

Demo: http://jsfiddle.net/kYdex/1/

Evans answered 5/7, 2011 at 14:52 Comment(0)
P
-2

If getElementsByClassname does not support is error in some old browsers Simply try var modal = document.getElementById('myModal'); modal.onclick= function(){ Then do what ever onclick function or another function by using getElementById modal.style.display = "none"; }

Pornocracy answered 17/2, 2017 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.