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

Why Doesn't `getElementsByClassName` Work with `forEach` Directly?

DDD
Release: 2024-12-01 11:01:14
Original
757 people have browsed it

Why Doesn't `getElementsByClassName` Work with `forEach` Directly?

Array.forEach Method: Compatibility with getElementsByClassName

While attempting to iterate over DOM elements using the getElementsByClassName method, developers may encounter a peculiar error: "document.getElementsByClassName('myclass').forEach is not a function." Despite the presence of both getElementsByClassName and Array.forEach in Firefox 3, the error persists.

The confusion arises because the result of getElementsByClassName is not an Array. In modern browsers, it is an HTMLCollection, a specialized collection tailored for HTML elements. Although it possesses array-like properties, it is not a true array.

To resolve the issue and successfully iterate over the elements, developers can employ a trick: they can call Array's forEach method, passing the HTMLCollection as the this value:

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

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

This technique allows the iteration to proceed as expected. Alternatively, developers can use Array.from, available in ES6 environments, to convert the HTMLCollection to an Array before iterating:

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

By utilizing these techniques, developers can effectively iterate over DOM elements obtained via getElementsByClassName, ensuring compatibility with the Array.forEach method.

The above is the detailed content of Why Doesn't `getElementsByClassName` Work with `forEach` Directly?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template