Question

I have a script (helped out by @briguy37 Remove multiple elements with same name using removeChild?) that removes all the elements with a certain class name by using a for loop and using removeChild. Its working perfectly in FF, but in IE, i get the error

Object doesnt support this property or method

The project can be viewed at: http://jsfiddle.net/U8xkg/31/

The error refers to the line:

var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo');

Any ideas?

Thanks.

Was it helpful?

Solution

document.getElementsByClassName = function(class_name)
{
    var all = this.getElementsByTagName('*');
    var matchArray = new Array();
    var re = new RegExp("(?:^|\\s)" + class_name + "(?:\\s|$)");
    for (var i = 0, l = all.length; i < l; i++)
    {
        if (re.test(all[i].className))
            matchArray.push(all[i]);
    }
    return matchArray;
}

OTHER TIPS

Unfortunately there is no method getElementsByClassName in IE.

check whether there is such method - getElementsByClassName. if not, check, whether querySelectorAll method is supported. If, one again, not, you should better use some framework to fetch nodes. Especially this code is intended to be cross-browser.

If you aren't using any framework in your project (jQuery, YUI, etc...), then do your self a favor and increase your productivity by at least including the Sizzle library that adds CSS3 selector capabilities to any browser, yet is quite lightweight and fast. That will let you just do:

var childNodesToRemove = Sizzle(".foo");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top