What is the Fastest way to convert JavaScript NodeList to Array

The fastest way to convert NodeList to Array in JavaScript is to use the “Array.prototype.from()” method. The Array.prototype.from() method is used to create a shallow-copied new Array instance from an array-like or iterable object.

Syntax

let main_arr = Array.from(nodelist)

Example

let nodelist = document.querySelectorAll('div');

let main_arr = Array.from(nodelist);

console.log(main_arr);

for (let val of main_arr) {
  console.log(val);
}

This is a straightforward way to convert a NodeList to an array and then process each element. If you run this code in a browser’s console on a webpage with div elements, you should see the array of div elements followed by each div element being logged.

Related posts

JavaScript ES6 Iterable to Array

JavaScript Map to Array

JavaScript Set to Array

Leave a Comment