Home > Web Front-end > JS Tutorial > Why Doesn't `forEach` Work Directly on `HTMLCollection`?

Why Doesn't `forEach` Work Directly on `HTMLCollection`?

Barbara Streisand
Release: 2024-12-01 03:01:09
Original
470 people have browsed it

Why Doesn't `forEach` Work Directly on `HTMLCollection`?

Iterating over HTMLCollection with Array.forEach

In this dilemma, a developer attempts to iterate over DOM elements using document.getElementsByClassName("myclass").forEach only to encounter an error stating, ".forEach is not a function."

Understanding HTMLCollection

The key to resolving this error lies in understanding the nature of the result returned by getElementsByClassName. Contrary to its name, it doesn't produce an array but rather an HTMLCollection. HTMLCollection, much like NodeList, follows the DOM4 specification and differs from a traditional array in subtle yet significant ways.

Converting HTMLCollection to Array

To utilize the powerful forEach method, one must first transform the HTMLCollection into an array. Several methods can accomplish this conversion:

Using Array.prototype.forEach.call:

var els = document.getElementsByClassName("myclass");

Array.prototype.forEach.call(els, function(el) {
  // Do stuff here
  console.log(el.tagName);
});
Copy after login

Using [].forEach.call:

[].forEach.call(els, function (el) {...});
Copy after login

Using Array.from (ES6):

Array.from(els).forEach((el) => {
  // Do stuff here
  console.log(el.tagName);
});
Copy after login

By converting the HTMLCollection to an array, one can leverage the plethora of array methods, including forEach, to process and manipulate the DOM elements efficiently.

The above is the detailed content of Why Doesn't `forEach` Work Directly on `HTMLCollection`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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