Let’s say we have the following unordered list and, we want to iterate over them.
First, we select all the list items using
document.querySelectorAll() method and store the result into the
menuItems in console, we get the output in the form of
NodeList has a
forEach() method that can be used to iterate over the unordered list as follows:
Since NodeList looks like an array(is not an array) you might be thinking of using other array methods like
map() etc… However, remember NodeList doesn’t inherit from Array.
Let’s understand this better by using the
map() method on
When we use
Uncaught TypeError: menuItems.map is not a function.
To solve this issue, we need to first convert the
menuItems in Array. This conversion is really simple, using the spread operator.
As we can see, after converting the