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);