getElementsByClassName not working in IE?

Hi There, i’m a javascript newbie. Based on the book “Simply Javascript”, i can’t seem to get the getElementsByClassName function to work on IE. I don’t know why.

There is no error on IE. I’ve tried with IE Tester and i get this error:

Object doesn’t support this property or method

Additional Note: This works on Firefox and Chrome


function getElementsByClassName(className) {// Get a list of all elements in the document
    // For IE
    if (document.all) {
        var allElements = document.all;
    } else {
        var allElements = document.getElementsByTagName("*");
    }

    // Empty placeholder to put in the found elements with the class name
    var foundElements = [];

    for (var i = 0, ii = allElements.length; i < ii; i++) {
        if (allElements[i].className == className) {
            foundElements[foundElements.length] = allElements[i];
        }
    }

    return foundElements;

}

// Getting an item by class name

var listItem = document.getElementsByClassName("quirky");

for (var i = 0, ii = listItem.length; i < ii; i++) {
    alert(listItem[i].nodeName);
}

Thank you for reading this. Any help is greatly appreciated :slight_smile:

The problem is with this line here:

document.getElementsByClassName("quirky")

That line is not using the function you created. Instead it is trying to use the built-in method that the web browser has. IE doesn’t have it, so IE complains.

You can fix that by checking if the browser implements document.getElementsByClassName. If it doesn’t, add it.


if (!document.getElementsByClassName) {
    document.getElementsByClassName = function (className) {
        // contents of the function here
    }
}

I still don’t know how to get IE to use prototypal inheritance so that you can a similar technique from any element, but at least the above will work when you use document.getElementsByClassName(…)