NodeList to Array in Javascript

If you are a Javascript developer, you must have faced the awkward moment: NodeLists. They are like arrays, but not. Some very useful array functions like map, filter, etc. cannot be used on them. So, you might need a way to convert a NodeList to Array.

NodeList to Array

Assuming you have multiple div elements.


var nodeList = document.querySelectorAll("div"),
	nodeArray;
// long version
nodeArray = Array.prototype.slice.call(nodeList);
// short version
nodeArray = [].slice.call(nodeList)
// ES6 version
nodeArray = [...nodeList]

Now you can use Array functions on nodeArray. Note that currently (2019) ES6 is only supported by the newest browsers. So, use first two methods.

Tagged: Javascript
Liked the article? Follow me on Twitter, or help Hyvor grow by funding Hyvor Talk.
Latest on Hyvor Developer
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Image for The Best Way to Perform MYSQLI Prepared Statements in PHP
The Best Way to Perform MYSQLI Prepared Statements in PHP
Related Articles
0