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');
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; }
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');
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!