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

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

Mary-Kate Olsen
Release: 2024-10-20 06:42:02
Original
775 people have browsed it

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

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

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!

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!