Home > Web Front-end > JS Tutorial > How to Use getElementsByClassName() in Internet Explorer?

How to Use getElementsByClassName() in Internet Explorer?

Mary-Kate Olsen
Release: 2024-11-05 19:15:02
Original
374 people have browsed it

How to Use getElementsByClassName() in Internet Explorer?

Compatibility of document.getElementsByClassName in IE

Internet Explorer presents a challenge when attempting to retrieve an array of elements with a specific class using document.getElementsByClassName(). To overcome this limitation, a custom solution is necessary.

Jonathan Snook's Method

One approach to emulating document.getElementsByClassName() in IE is utilizing Jonathan Snook's function, which iterates through all elements within a node using getElementsByTagName(*) and filters them based on the presence of the desired class.

IE Incompatibility

Despite implementing Snook's solution, an error may still occur in IE stating, "Object doesn't support this property or method." This is because getElementsByClassName() is not a direct method of the document object in IE.

Corrected Implementation

The correct implementation of Snook's function requires specifying the target node explicitly:

var tabs = getElementsByClassName(document.body, 'tab');
Copy after login

IE8 Support

For IE8 and later versions, a simplified approach can be utilized:

if (!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
        return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}
Copy after login

This code snippet defines getElementsByClassName() as a method of the document object and also makes it available to individual elements through Element.prototype.getElementsByClassName().

Usage

Once implemented, the getElementsByClassName() method can be used as follows:

var tabs = document.getElementsByClassName('tab');
Copy after login

The above is the detailed content of How to Use getElementsByClassName() in Internet Explorer?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template