Home > Web Front-end > JS Tutorial > body text

How Can I Retrieve Elements by Class in JavaScript, Especially for IE Compatibility?

Susan Sarandon
Release: 2024-11-05 21:41:02
Original
874 people have browsed it

How Can I Retrieve Elements by Class in JavaScript, Especially for IE Compatibility?

Retrieving Elements by Class in JavaScript, Including IE Compatibility

Getting an array of elements based on their class is a common task in JavaScript. However, for browsers that do not natively support document.getElementsByClassName(), such as IE, an alternative approach is needed.

One popular solution is the function by Jonathan Snook. This function employs a regular expression to test the className property of each element. However, in IE, it throws an error stating "Object doesn't support this property or method."

The key is to realize that getElementsByClassName() is not a method of the document object. Instead, it should be called directly on the node where you want to search for elements:

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

For IE8 , a more concise approach is to polyfill the getElementsByClassName() function:

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

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

With these techniques, you can retrieve elements by class, ensuring compatibility with IE and other browsers.

The above is the detailed content of How Can I Retrieve Elements by Class in JavaScript, Especially for IE Compatibility?. 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