How to convert a Nodelist to an Array in JavaScript

In my latest little Project, creating a nice browser game using mostly Vanilla JS, I came across a small difficulty when dealing with Nodelists. Therefore I needed to learn how to convert a Nodelist to an Array in JavaScript and I am going to show you how to do that today.

Convert nodelist to array in javascript

How to convert a Nodelist to an Array in JavaScript

Recycling information stored in a Nodelist, which actually updates automatically, was not really useful for my purposes. Therefore, I converted my Nodelists into Arrays, which made it more static and a bit more convenient.

Converting these lists into a single Array is actually quite simple, here is how it goes:

let nList = document.querySelectorAll(".col");

let arr = Array.from(nList);

Having created a few <div class=”col”> before in my HTML file, I selected these with the first line and they automatically got stored into a Nodelist.

In order to convert that Nodelist into an Array, I created a new variable and use the Javascript method Array.from();

By storing my Nodelist via Array.from(nList) into the new variable called “arr”, I now have a fully functional Array available and can utilize it for all task necessary.

Please note that for this Javascript method there is no Browser Support for IE.

For further information, or for a polyfill to push back to up to IE6, you can look up the MDN documentation.

If you also would like to know how to Sort Numbers in JavaScript, we got you all covered.

Conclusion

As you can see, converting a Nodelist into an Array in Javascript is not really hard. However, it greatly will help you. For my case, after using this method, I finally could play around with the different values in my array. Especially when restarting my browser game, and re-applying all different functions to my HTML elements, I could see the benefits.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap