Issues with forEach() in Microsoft Browsers for DOM Collections
As developers, we often rely on the forEach() method to traverse and manipulate DOM collections. However, we may encounter the frustrating error "Object doesn't support property or method 'forEach'" in Internet Explorer 11 and Edge.
Understanding DOM Collections
To resolve this issue, we must understand that DOM methods like querySelectorAll return collections, namely NodeList or HTMLCollection, which do not inherently support forEach().
Polyfilling forEach()
Since NodeList is specified to have forEach(), we can safely polyfill it:
<code class="js">if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; }</code>
Ensuring Iterability
NodeList and HTMLCollection are iterable, but older browsers may not implement this. We can polyfill iterability as well:
<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>
With these polyfills in place, we can successfully use forEach() on NodeList and HTMLCollection even in IE11 and Edge.
Example Usage
<code class="js">var color_btns = document.querySelectorAll('#color > p'); color_btns.forEach(function(color) { // Our custom logic here... });</code>
Additional Considerations
Some legacy DOM libraries may be confused by adding forEach() to HTMLCollection. In such cases, only polyfill forEach() on NodeList.
The above is the detailed content of Why is \'Object doesn\'t support property or method \'forEach\'\' Thrown for DOM Collections in Microsoft Browsers?. For more information, please follow other related articles on the PHP Chinese website!