Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, what is the best way to convert a NodeList to an array?

The DOM method document.querySelectorAll() (and a few others) return a NodeList.

To operate on the list, e.g. using forEach(), the NodeList must first be converted to an Array.

What's the best way to convert the NodeList to an Array?

like image 250
cc young Avatar asked Sep 18 '11 05:09

cc young


People also ask

How do I turn querySelectorAll into an array?

You can convert it to an array by using the slice method from the Array prototype: var elList = document. querySelectorAll('. viewcount'); elList = Array.

Can we convert set to array in JavaScript?

By using Array. from() method: This method returns a new Array from an array like object or iterable objects like Map, Set, etc.

What is the difference between NodeList and array?

A NodeList may look like an array, but in reality, they both are two completely different things. A NodeList object is basically a collection of DOM nodes extracted from the HTML document. An array is a special data-type in JavaScript, that can store a collection of arbitrary elements.


2 Answers

With ES6 you can simply do:

const spanList = [...document.querySelectorAll("span")]; 
like image 139
Freezystem Avatar answered Oct 21 '22 01:10

Freezystem


With ES6 you can use Array.from(myNodeList). Then use your favourite array method.

var myNodeList = document.querySelectorAll('.my-selector');  // ALT 1 Array.from(myNodeList).forEach(function(el) {   console.log(el); }); 

Use an ES6 shim to make this work in older browsers too.


If you are using a transpiler (for example Babel) there are two more alternatives:

var myNodeList = document.querySelectorAll('.my-selector');  // ALT 2 for (var el of myNodeList) {   el.classList.add('active'); // or some other action }  // ALT 3 [...myNodeList].forEach((el) => {   console.log(el); }); 
like image 23
sandstrom Avatar answered Oct 21 '22 01:10

sandstrom