• JavaScript Video Tutorials

JavaScript - DOM Node Lists



DOM Node Lists

The Node lists are similar to an array or HTML collection containing the HTML elements. However, it is not the same as the array or HTML collection.

All modern browsers return the node list when you use querySelectorAll() method and childNodes properties.

You can traverse the NodeList as an array but can't use other array methods like map(), filter(), etc. with node lists.

Example

Using the forEach() method to traverse the node list elements

In the below program, we have defined four <p> elements containing the various languages.

After that, we use the querySelectorAll() method to get all elements having a class name equal to 'lang' in the node list. After that, we traverse the node list using the forEach() method and print the HTML of each element.

<DOCTYPE html>
<html>
<body>
   <p class = "lang"> English </p>
   <p class = "lang"> German </p>
   <p class = "lang"> Arabic </p>
   <p class = "lang"> Hindi </p> <br>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      output.innerHTML += "All languages are: <br>";
      const langs = document.querySelectorAll('.lang');
      langs.forEach((language) => {
         output.innerHTML += language.innerHTML + '<br>';
      })
   </script>
</body>
</html>

Example: Getting the length of the node list

In the below code, we have used the 'length' property of the node list to count the number of nodes in the node list.

<DOCTYPE html>
<html>
<body>
   <div class = "fruit"> Apple </div>
   <div class = "fruit"> Orange </div>
   <div class = "fruit"> Banana </div>
   <div class = "fruit"> Mango </div>
   <div id = "output">Total number of fruits are : </div>
   <script>
      const fruits = document.querySelectorAll('.fruit');
      document.getElementById('output').innerHTML += fruits.length;
   </script>
</body>
</html>

Difference between HTMLCollection and NodeList

The HTML collection and Node list look similar, but there is a minor difference between them, which we have explained in the table below.

Feature HTMLCollection NodeList
Return by Generally, getElementByClassName(), getElementByTagName methods, and children properties return the HTML collection. Generally, the querySelectorAll() method and childNodes property return the Node list.
Array methods It supports limited array methods. It also supports limited array methods like forEach().
Live collection Some browser supports live collection with HTML collection. It updates if you update the DOM element.
Advertisements