The forEach() method, despite its widespread support, encounters some issues when used with querySelectorAll in recent versions of Internet Explorer (11) and Edge.
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.
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" && NodeList.prototype && !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" && Symbol.iterator && typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype[Symbol.iterator]) { Object.defineProperty(NodeList.prototype, Symbol.iterator, { value: Array.prototype[Symbol.iterator], writable: true, configurable: true }); }</code>
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!