Nodelist To Array

00:00
BACK TO HOME

Nodelist To Array

10xTeam November 05, 2022 2 min read

layout: bpost title: “Convert a NodeList to array with JavaScript” image: “images/content/updating-angular-cli-projects.png” excerpt: “This code example will show you how to convert a NodeList to array with JavaScript.” categories: [javascript] permalink: /nodelist-to-array-javascript/ tags: [javascript] —

This code example will show you how to convert a NodeList to array with JavaScript.

The common method to convert a NodeList to array is to use the call() method to execute the Array.prototype.slice() method on your NodeList, as follows:

// Get all elements as a NodeList
var elmnts = document.querySelectorAll('a');

// Convert elements NodeList to an array
var aArr = Array.prototype.slice.call(elmnts);

This is working but there is now a modern method you can use to do the same thing: Array.from().

The Array.from() method returns a new array from an existing array, or from an array-like object such as NodeList:

// Get all elmnts as a NodeList
var elmnts = document.querySelectorAll('a');

// Convert elmnts NodeList to an array
var aArr = Array.from(elmnts);

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?