Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-20 06:44:02
Original
528 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!