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
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Laravel High CPU Usage Because of File-based Session Storage
Laravel High CPU Usage Because of File-based Session Storage
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Related Articles
1