Array.forEach Issue with HTMLCollections in Edge and Internet Explorer
Introduction:
DOM collection properties and methods, such as querySelectorAll, return collections, specifically NodeLists (for querySelectorAll) or HTMLCollections (for methods like getElementsByTagName). These collections differ from regular arrays in their functionality.
The Problem with forEach:
NodeList and HTMLCollection do not natively support the forEach method. This is why you encounter the error "Object doesn't support property or method 'forEach'" in Microsoft's Edge and Internet Explorer browsers.
Solutions:
1. Polyfill forEach for NodeList:
To make forEach work with NodeList, you can define it as:
<code class="js">if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; }</code>
2. Polyfill Iterability for NodeList and HTMLCollection:
As NodeList and HTMLCollection are specified to be iterable, you can polyfill that using:
<code class="js">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>
Additional Notes:
The above is the detailed content of How to Fix Array.forEach Issues with HTMLCollections in Edge and Internet Explorer?. For more information, please follow other related articles on the PHP Chinese website!