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.

<ul id="menu">
  <li>🍕Pizza</li>
  <li>🍩 Doughnut</li>
  <li>🍔 Hamburger</li>
</ul>

First, we select all the list items using document.querySelectorAll() method and store the result into the menuItems variable.

const menuItems = document.querySelectorAll('#menu li')

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

const menuItems = document.querySelectorAll('#menu li')
console.log(menuItems) // NodeList(3) [li, li, li]

NodeList has a forEach() method that can be used to iterate over the unordered list as follows:

menuItems.forEach(item => console.log(item))
// OUTPUT
// <li>🍕Pizza </li>
// <li>🍩 Doughnut</li>
// <li>🍔 Hamburger</li>

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.

menuItems.forEach(item => console.log(item))
// Uncaught TypeError: menuItems.map is not a function

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.

;[...menuItems].forEach(item => console.log(item))
// OUTPUT
// <li>🍕Pizza </li>
// <li>🍩 Doughnut</li>
// <li>🍔 Hamburger</li>

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

Related Posts

JavaScript
How to insert an element before another using JavaScript?
June 23, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media