A NodeList is a collection of nodes similar to an array. It is basically a collection of DOM elements. In order to work with a NodeList, we may convert it to a regular JavaScript array so that the features and flexibility of an array could be used. A NodeList is a host object and is not subject to the usual rules that apply to native JavaScript objects.
Approach: 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. This method is used to create a shallow-copied new Array instance from an array-like or iterable object. The NodeList we are converting from in this case is the array-like object.
Syntax:
let my_arr = Array.from( given_nodelist )
Example: This example shows the use of the above-explained approach.
HTML
< body > < h1 style = "color: green" > neveropen </ h1 > < div class = "content primary" > < p > A Computer Science portal for neveropen. 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 > |
Output: