logo
post image

Looping through querySelectorAll() with Javascript

Use-Cases of this code snippet

  • Know how to iterate through list of nodes returned by document.querySelectorAll().
  • Know how to loop through a NodeList object.

List of nodes returned by querySelectorAll() can be looped through using the forEach() method of the returned NodeList object.

HTML

<div class="item" data-id="1">Item 1</div>
<div class="item" data-id="2">Item 2</div>
<div class="item" data-id="3">Item 3</div>
<div class="item" data-id="4">Item 4</div>
<div class="item" data-id="5">Item 4</div>
<div class="item" data-id="6">Item 6</div>
<div class="item" data-id="7">Item 7</div>
<div class="item" data-id="8">Item 8</div>

Javascript

document.querySelectorAll(".item").forEach(function(element) {
    // element refers to the DOM node

    console.log(element.getAttribute('data-id'));
});

Result :

1
2
3
4
5
6
7
8

Notes

  • querySelectorAll() returns a NodeList object, which is array-like, but not an array. It has its own forEach() method that can be used to used to loop through it (this is different from the forEach statement used to loop arrays).
  • The NodeList returned by querySelectorAll() can be converted to a proper Javascript array using Array.from() method.

    Array.from(document.querySelectorAll(".item")).forEach(function(element) {
        // element refers to the DOM node
    
        console.log(element.getAttribute('data-id'));
    });