Open In App

Fastest way to convert JavaScript NodeList to Array

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There are many ways to convert a NodeList to a JavaScript array but the fastest of all is a new method from ES6. In ES6, we can now simply create an Array from a NodeList using the Array.from() method.

Approach

The JavaScript Array.from() method is used to create a new array instance from a given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance, and in the case of integer values, a new array instance simply takes the elements of the given array.

Syntax:

let my_arr = Array.from( given_nodelist );

Example: This example shows the use of the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
</head>
 
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
    <div class="content primary">
 
        <p>
            A Computer Science portal for geeks.
            It contains well written, well thought
            and well explained computer science and
            programming articles, quizzes and
            placement guides.
        </p>
 
    </div>
    <div class="content secondary">
 
        <p>This example demonstrates the fastest
            way to convert from a NodeList to an array.
        </p>
 
    </div>
    <script>
        // This will act select all div DOM
        elements in the page
        let nodelist =
            document.querySelectorAll('div');
 
        // This will convert the DOM NodeList
        // to a JavaScript Array Object
        let my_arr = Array.from(nodelist);
 
        // Display the array in the console
        console.log(my_arr);
 
        // Display all the values of the
        // array in the console
        for (let val of my_arr) {
            console.log(val);
        }
    </script>
 
</body>
 
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads