Home > Article > Web Front-end > How to Make document.getElementsByClassName Work in Internet Explorer?
Compatibility of document.getElementsByClassName with Internet Explorer
The document.getElementsByClassName method provides a convenient way to retrieve elements with a specific class. However, it faces compatibility issues with Internet Explorer (IE).
Jonathan Snook's Solution
One common approach to address this issue is to use Jonathan Snook's custom function, getElementsByClassName. This function utilizes a regular expression to search for elements with the desired class name.
However, IE may still encounter an error with this solution due to an incorrect invocation. The function should be invoked as follows:
function getElementsByClassName(node, classname) {...} tabs = getElementsByClassName(document.body, 'tab');
Instead of:
document.getElementsByClassName(document.body, 'tab');
Other Compatible Options
If support for IE8 and above is sufficient, you can implement the following polyfill for document.getElementsByClassName:
if (!document.getElementsByClassName) { document.getElementsByClassName = function (className) { return this.querySelectorAll('.' + className); }; Element.prototype.getElementsByClassName = document.getElementsByClassName; } tabs = document.getElementsByClassName('tab');
Conclusion
By adjusting the invocation of Jonathan Snook's function or using the provided polyfill, you can overcome compatibility issues with document.getElementsByClassName in IE.
The above is the detailed content of How to Make document.getElementsByClassName Work in Internet Explorer?. For more information, please follow other related articles on the PHP Chinese website!