Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to convert a DOM nodelist to an array using JavaScript ?

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: 

HTML




<body>
    <p>Hello neveropen 1</p>
    <p>Hello neveropen 2</p>
    <p>Hello neveropen 3</p>
    <p>Hello neveropen 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: 

HTML




<body>
    <p>Hello neveropen 1</p>
    <p>Hello neveropen 2</p>
    <p>Hello neveropen 3</p>
    <p>Hello neveropen 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: 

HTML




<body>
    <p>Hello neveropen 1</p>
    <p>Hello neveropen 2</p>
    <p>Hello neveropen 3</p>
    <p>Hello neveropen 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.
 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments