Categories
JavaScript Answers

How to fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript?

Spread the love

Sometimes, we want to fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript.

In this article, we’ll look at how to fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript.

How to fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript?

To fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript, we can use the spread operator to convert the node list returned by getElementsByClassName to an array.

For instance, we write

[...document.getElementsByClassName("myClass")].forEach((v) => {
  //...
});

to get the elements with class myClass with getElementsByClassName.

Then we spread the entries in the node list returned by getElementsByClassName into an array.

Next, we call forEach with a callback to loop through each element.

Conclusion

To fix using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” error with JavaScript, we can use the spread operator to convert the node list returned by getElementsByClassName to 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 *