Home > Web Front-end > JS Tutorial > How to Retrieve Elements by Class Name in Internet Explorer?

How to Retrieve Elements by Class Name in Internet Explorer?

Mary-Kate Olsen
Release: 2024-11-06 00:48:02
Original
958 people have browsed it

How to Retrieve Elements by Class Name in Internet Explorer?

getElementsByClassName() Compatibility with IE

Question: How to effectively retrieve an array of elements with a specific class, considering IE compatibility limitations?

Answer:

Document.getElementsByClassName() is a modern method not supported by IE. Instead, consider the following approaches:

Custom Function (IE6 ):

Define a custom function to emulate getElementsByClassName(). This involves traversing the DOM and testing elements' class names against a provided class name:

<code class="js">function getElementsByClassName(node, className) {
    var a = [];
    var re = new RegExp('(^| )' + className + '( |$)');
    var els = node.getElementsByTagName('*');
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
}

// Usage:
var tabs = getElementsByClassName(document.body, 'tab');</code>
Copy after login

querySelectorAll (IE8 ):

If supporting IE8 or above is sufficient, extend the document and Element objects to support querySelectorAll():

<code class="js">if (!document.getElementsByClassName) {
    document.getElementsByClassName = function (className) {
        return this.querySelectorAll('.' + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}

// Usage:
var tabs = document.getElementsByClassName('tab');</code>
Copy after login

Ensure that you call getElementsByClassName() with the desired node as the first argument, as it is not a document method. By implementing one of these solutions, you can retrieve elements by class name, ensuring compatibility with a wider range of browsers, including IE.

The above is the detailed content of How to Retrieve Elements by Class Name 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