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
Written By
Supun Kavinda
Written On
Apr 17, 2019
Last Updated On
Apr 17, 2019
Latest on Hyvor Developer
Creating a Real-Time Chat App with PHP and Node.js
All About MYSQLI Prepared Statements in PHP
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
PHP Contact Form - The Email Method
Related Articles
0