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."
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.
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); });
Using [].forEach.call:
[].forEach.call(els, function (el) {...});
Using Array.from (ES6):
Array.from(els).forEach((el) => { // Do stuff here console.log(el.tagName); });
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!