Open In App

How to convert a DOM nodelist to an array using JavaScript ?

NodeList objects are the collection of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). Although NodeList is not an actual Array but it is possible to iterate over it with the help of forEach() method. NodeList can also be converted into actual array by following methods.

Method 1: By using Array.prototype.slice.call() method.



Syntax: 

const array = Array.prototype.slice.call(nodeList); // Normal Method

const array = [].slice.call(nodeList);                 // Condensed Method

Example: 






<body>
    <p>Hello geeks 1</p>
    <p>Hello geeks 2</p>
    <p>Hello geeks 3</p>
    <p>Hello geeks 4</p>
  
    <script>
        // This is nodeList
        const nodeList = document.querySelectorAll('p');
        console.log(nodeList);
          
        // Converting using Array.prototype.slice.call
        const array1 = Array.prototype.slice.call(nodeList);
        console.log(array1);
    </script>
</body>

Output:

Method 2: With the help of Array.from() method.

Syntax: 

const array = Array.from(nodeList);

Example: 




<body>
    <p>Hello geeks 1</p>
    <p>Hello geeks 2</p>
    <p>Hello geeks 3</p>
    <p>Hello geeks 4</p>
  
    <script>
        // This is nodeList
        const nodeList = document.querySelectorAll('p');
        console.log(nodeList);
          
        // Converting to array using Array.from() method
        const array = Array.from(nodeList);
        console.log(array);
    </script>
</body>

Output:

Method 3: Using ES6 spread syntax, it allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected. 

Syntax: 

const array = [ ...nodeList ]

Example: 




<body>
    <p>Hello geeks 1</p>
    <p>Hello geeks 2</p>
    <p>Hello geeks 3</p>
    <p>Hello geeks 4</p>
  
    <script>
        // This is nodeList
        const nodeList = document.querySelectorAll('p');
        console.log(nodeList);
          
        // Converting using Spread syntax
        const array1 = [...nodeList];
        console.log(array1);
    </script>
</body>

Output:

Note: Method 2 and Method 3 may not work in older browsers properly but will work fine in all modern browsers.
 


Article Tags :