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>
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>
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!