HomeTutorsContact

How to iterate through NodeList using Javascript?

By Gulshan Saini
Published in JavaScript
July 09, 2020
1 min read

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 variable.

On logging menuItems in console, we get the output in the form of NodeList array.

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 filter(), map() etc… However, remember NodeList doesn’t inherit from Array.

Let’s understand this better by using the map() method on menuItems.

When we use map() on menuItems Javascript throw error 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 menuItems to Array, the Javascript engine no more throws any error.

Output

Open developer console to view results

Tags

#dom-manipulation
Previous Article
Shortcut to clear site data from the Google Chrome command line

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to insert an element before another using JavaScript?

June 23, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media