DEV Community

loading...

Easiest way to convert HTMLCollection into an Array!

hasnaindev profile image Muhammad Hasnain ・2 min read

There are two ways in which you can convert an HTMLCollection or a NodeList into an array.

If you don't know what an HTMLCollection and a NodeList is, or why you would need to convert them into a normal Array, hold tight, I'll explain them soon enough! 🐢

// First, pre-ES6 way.
var htmlCollection = document.getElementsByClassName('btn');
htmlCollection = Array.prototype.slice.call(elements);

// Or you could do the same thing using ES6 syntax.
var nodeList = document.querySelectorAll('.btn');
nodeList = [...nodeList];

// 🎉🎉
Enter fullscreen mode Exit fullscreen mode

What is HTMLCollection and NodeList?

When you use methods like getElementsByClassName or querySelectorAll they return an HTMLCollection or NodeList respectively instead of an Array.

HTMLCollection contains HTML elements whereas NodeList goes a few steps further, it not only returns a list of HTML elements but can also return Nodes like TextNode and has additional methods list NodeList.forEach.

For a more detailed discussion on the topic, you may read this stackoverflow post called: The difference between HTMLCollection, NodeList and Array.

Why convert them into an Array?

The only reason to convert an HTMLCollection and NodeList to an Array is, if you want to use higher order functions like forEach, map, filter and reduce.

There are a lot of use cases, for instance, let's say you have elements that contain a data-src property along with lazy-load class. If you want to access the data-src and filter out all the elements that don't have data-src or are empty, you may do the following.

Use Case

var lazyLoadables = [...document.querySelectorAll('.lazy-load')]
  .filter((element) => element.getAttribute('data-src').trim());

lazyLoadImages(lazyLoadables);
Enter fullscreen mode Exit fullscreen mode

By doing this, you made sure only to pass the elements that have a source that needs to be loaded when it is required.

Discussion (2)

pic
Editor guide
Collapse
traekwells profile image
Traek Wells • Edited

This is a nice write-up. I'd like to add to your first example an even easier way (at least easier by the amount of typing you have to do) and that's Array.from()

var htmlCollection = document.getElementsByClassName('btn');
htmlCollection = Array.from(htmlCollection);
Enter fullscreen mode Exit fullscreen mode

or to make it a bit shorter

var htmlCollection = Array.from(document.getElementsByClassName('btn'))
Enter fullscreen mode Exit fullscreen mode

I use this all the time and it works like a charm.

Collapse
hasnaindev profile image
Muhammad Hasnain Author

Thank you Traek, your solution is neat! 👏