Home  >  Article  >  Web Front-end  >  Why doesn\'t forEach() work on querySelectorAll in recent Microsoft browsers?

Why doesn\'t forEach() work on querySelectorAll in recent Microsoft browsers?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 06:44:02530browse

Why doesn't forEach() work on querySelectorAll in recent Microsoft browsers?

forEach on querySelectorAll Not Working in Recent Microsoft Browsers

The forEach() method, despite its widespread support, encounters some issues when used with querySelectorAll in recent versions of Internet Explorer (11) and Edge.

Understanding the Issue

NodeList and HTMLCollection, which are collections representing matching DOM elements, lack the forEach() method natively in older Microsoft browsers. These collections, however, are iterable, allowing for looping through them using alternative methods like for-of.

Resolving the Issue

Polyfilling forEach()

You can manually add the forEach() method to NodeList and HTMLCollection in browsers that don't natively support it. This is a simple and effective solution:

<code class="javascript">if (typeof NodeList !== "undefined" &amp;&amp; NodeList.prototype &amp;&amp; !NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach;
}</code>

Polyfilling Iterability

If a browser has ES2015 features but still lacks NodeList iterability, you can polyfill that as well:

<code class="javascript">if (typeof Symbol !== "undefined" &amp;&amp; Symbol.iterator &amp;&amp; typeof NodeList !== "undefined" &amp;&amp; NodeList.prototype &amp;&amp; !NodeList.prototype[Symbol.iterator]) {
  Object.defineProperty(NodeList.prototype, Symbol.iterator, {
    value: Array.prototype[Symbol.iterator],
    writable: true,
    configurable: true
  });
}</code>

Conclusion

By polyfilling forEach() and iterability, you can overcome the limitations of older Microsoft browsers and ensure consistent behavior of your code when working with NodeList and HTMLCollection collections.

The above is the detailed content of Why doesn\'t forEach() work on querySelectorAll in recent Microsoft browsers?. 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