Sometimes, we want to correctly iterate through getElementsByClassName with JavaScript.
In this article, we’ll look at how to correctly iterate through getElementsByClassName with JavaScript.
How to correctly iterate through getElementsByClassName with JavaScript?
To correctly iterate through getElementsByClassName with JavaScript, we spread the node list into returned by getElementsByClassName
into an array.
For instance, we write
[...document.querySelectorAll(".edit")].forEach((button) => {
// ...
});
to select all elements with class edit
with querySelectorAll
and return a node list with them.
Then we use ...
to spread the node list items into an array.
We then call forEach
with a callback to loop through the elements.
We get the element from the button
parameter.
Conclusion
To correctly iterate through getElementsByClassName with JavaScript, we spread the node list into returned by getElementsByClassName
into an array.