How to iterate over DOM elements using JavaScript

published: 27 Aug 2022

2 min read

How to iterate over DOM elements using JavaScript

The querySelectorAll() method is used for selecting all elements of a specific type in JavaScript. It returns a list of DOM elements that match the specified selectors.

The returned list is not an array but a NodeList object containing a collection of nodes:

// select all anchor tags
const anchors = document.querySelectorAll('a.open-article')

// TODO: iterate over 'NodeList' elements and attach a click handler

There are many ways to loop through a NodeList object in JavaScript. Let us look at them.

forEach() Method

The simplest and easiest way to loop over the results returned by querySelectorAll() is by using the forEach() method. It executes the given function once for each node in the NodeList.

Here is an example:

anchors.forEach(anchor => {
  anchor.addEventListener('click', () => {
    console.log('Link is clicked!')
  })
})

The forEach() method for NodeList only works in modern browsers. If you want to support old browsers like Internet Explorer, use the following little hack instead:

;[].forEach.call(anchors, function (anchor) {
  anchor.addEventListener('click', function () {
    console.log('Link is clicked!')
  })
})

You can also use the spread operator to convert the NodeList to an Array object. This will give you access to all the array methods, including forEach():

;[...anchors].forEach(anchor => {
  anchor.addEventListener('click', () => {
    console.log('Link is clicked!')
  })
})

for...of Loop

Another way to loop through a NodeList object is using the ES6 for...of statement. It has a clean and concise syntax and is supported by all modern browsers:

for (const anchor of anchors) {
  anchor.addEventListener('click', () => {
    console.log('Link is clicked!')
  })
}

Modern browsers also support entries(), keys(), and values() methods on a NodeList object. These methods return an iterator allowing you to loop through all key-value pairs. The values are always Node objects:

// entries() can be replaced with keys() or values()
for (const anchor of anchors.entries()) {
  anchor.addEventListener('click', () => {
    console.log('Link is clicked!')
  })
}

for Loop

If you want to support the maximum number of browsers, including Internet Explorer (IE), the good old for loop is the way to go:

for (let i = 0; i < anchors.length; i++) {
  anchors[i].addEventListener('click', () => {
    console.log('Link is clicked!')
  })
}

3rd-Party Libraries

If you are already using jQuery, there is no need to use any of the above methods:

$('a.open-article').on('click', () => {
  console.log('Link is clicked!')
})

In JavaScript frameworks like Angular, React, and Vue, use Lodash's _.forEach method:

_.forEach(anchors, (anchor, key) => {
  anchor.addEventListener('click', () => {
    console.log('Link is clicked!')
  })
})

How to iterate over DOM elements using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, react, vue, programming
Check out what's on in the tag: javascript, react, vue, programming, array