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

code511788465541441 picture code511788465541441 · Jul 5, 2011 · Viewed 36.9k times · Source

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.

Answer

Peter picture Peter · Jul 5, 2011

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;
};