Search code examples
javascriptinternet-explorer-8internet-explorer-7internet-explorer-6dom-traversal

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


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.


Solution

  • 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.