Home  >  Article  >  Web Front-end  >  How to Fix Array.forEach Issues with HTMLCollections in Edge and Internet Explorer?

How to Fix Array.forEach Issues with HTMLCollections in Edge and Internet Explorer?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 06:42:02781browse

How to Fix Array.forEach Issues with HTMLCollections in Edge and Internet Explorer?

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" &amp;&amp; NodeList.prototype &amp;&amp; !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" &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>

Additional Notes:

  • for-of: Polyfilling iterability allows you to use the for-of loop syntax directly on collections.
  • Live Collection: HTMLCollection is a live collection, meaning changes to the DOM are reflected in the collection. NodeList is not live.
  • Compatibility: The provided polyfills target browsers without native forEach support, such as IE11.

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!

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