Home  >  Article  >  Web Front-end  >  How to Emulate getElementsByClassName() in Older Internet Explorers?

How to Emulate getElementsByClassName() in Older Internet Explorers?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 07:35:18160browse

How to Emulate getElementsByClassName() in Older Internet Explorers?

Cross-Browser Compatibility for getElementsByClassName()

The inability of IE6, IE7, and IE8 to utilize the getElementsByClassName() method presents a challenge when attempting to select elements based on their class attribute. However, there are solutions available to overcome this limitation without relying on third-party libraries like jQuery.

Emulating getElementsByClassName() in Older Internet Explorers

To mimic the functionality of getElementsByClassName() in IE6-8, the following script can be implemented:

<code class="javascript">document.getElementsByClassName = function(cl) {
  var retnode = [];
  var elem = this.getElementsByTagName('*');
  for (var i = 0; i < elem.length; i++) {
    if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]);
  }
  return retnode;
};</code>

Usage:

Simply include the script on your website, and it will extend the document object with a getElementsByClassName() method that works in all major browsers, including older versions of Internet Explorer.

Example:

<code class="html"><html>
<head>
  <script src="getElementsByClassName.js"></script>
  ...
</head>
<body>
  <div class="red-border"></div>
  ...
  var borderDivs = document.getElementsByClassName('red-border');
</body>
</html></code>

The above is the detailed content of How to Emulate getElementsByClassName() in Older Internet Explorers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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