Categories
JavaScript Answers

How to correctly iterate through getElementsByClassName with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *