DEV Community

Muhammad Hasnain
Muhammad Hasnain

Posted on • Edited on

Easiest way to convert HTMLCollection into an Array!

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];

// Or use Array.from method as suggested by Traek Wells in comments. 😎
var imageHtmlCollection = document.getElementsByTagName('img');
imageHtmlCollection = Array.from(htmlCollection);

// πŸŽ‰πŸŽ‰
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.

Top comments (1)

Collapse
 
hasnaindev profile image
Muhammad Hasnain

Thank you Traek, your solution is neat! πŸ‘