Home > Web Front-end > JS Tutorial > How Can I Use `document.getElementsByClassName` in Internet Explorer?

How Can I Use `document.getElementsByClassName` in Internet Explorer?

Barbara Streisand
Release: 2024-11-08 16:54:02
Original
901 people have browsed it

How Can I Use `document.getElementsByClassName` in Internet Explorer?

JavaScript document.getElementsByClassName Compatibility with IE

When attempting to obtain an element array with a specific class using document.getElementsByClassName, IE encounters compatibility issues. This method is not directly supported by IE.

Jonathan Snook's Method:

Using Jonathan Snook's getElementsByClassName function, which seeks elements based on a regular expression match, can lead to errors in IE. This is because the function is not defined as a method of document.

Solution:

To make the function compatible with IE, it should be called as a separate function without referring to document:

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;
}

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

IE8 Compatibility:

For IE8 and later, an alternative approach can be used:

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

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

This approach leverages the querySelectorAll method supported in IE8 , which operates similarly to getElementsByClassName.

The above is the detailed content of How Can I Use `document.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