At some point in your journey as a developer, you might have come across this error.
If you haven’t come across this error, maybe one day you will.
The above error occurs as a result of trying to use the forEach array method on an htmlCollection.
What is an htmlCollection
Well, an htmlCollection is a live and ordered list of nodes that represents a collection of HTML elements extracted from the DOM.
The htmlCollection may seem very much like an array, but it is not. That’s why whenever you try to use array methods like forEach(), push(), or join() on an htmlCollection, you get different types of errors similar to the one above.
Difference between a nodeList and an htmlCollection
Another collection of objects that happens to be very similar to the htmlCollection, is the nodeList. While they may both be an array-like list of html elements, the htmlCollection is a live list while the nodeList can either be live or static.
Difference between live and static
Being live means that any changes made in the underlying document will be automatically updated in the htmlCollection while being static means that whenever there is a change in the DOM, it doesn’t affect the htmlCollection.
Note: The nodeList may not be an array. However, it is possible to iterate through nodeLists using the forEach() method in some browsers.
In order to prevent the changes made in the DOM from affecting the elements in your htmlCollection, you will first need to convert the htmlCollection into an array.
How to Convert an htmlCollection into an Array
For instance, if we have an htmlCollection as follows:
var headers = document. document.getElementsByClassname(“heading”);
The above can easily be converted into an array by using the following syntax:
arrayOfHeaders = Array.from(headers);
2. Spread operator (…)
For example: If we have a method that returns an htmlCollection like:
var buttons = document.getElementsByClassname(“button”);
We can make use of the spread operator to input the values of buttons into an array and maybe store them into a variable if you want.
var arrayOfButtons = […buttons];
3. Slice() method
The slice() method can be used for converting an htmlCollection by creating a variable for the new array and using the following method:
var arr = .slice.call(document.getElementsByName(“classname”));
Methods that return a NodeList
Methods that return an htmlCollection
For a more detailed explanation, you can make reference to the documentation via the links below:
For htmlCollection: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection