How to convert an HTMLCollection object to an Array in JavaScript?

Published August 24, 2021

To convert an HTMLCollection object to an array, we can use the from() method from the global Array object in JavaScript.

TL;DR

// Get all the references to the elements with classname 'header'.
// The method return an HTMLCollection object.
const headers = document.getElementsByClassName("header");

// Convert HTMLCollection object to array
// using the Array.from() method
const headersArr = Array.from(headers);

console.log(headersArr); // [div.header, div.header]

For example, let's say we have a two div tags with same class name called header in the HTML template like this,

<!-- 2 div tags with same class name -->
<div class="header">Header 1</div>
<div class="header">Header 2</div>

So if we were to get all the elements with the class name called header, we can use the getElementsByClassName method from the global document object and pass the class name as an argument to the method. In our case, the class name is header.

It can be done like this,

// Get all the references to the elements with classname 'header'.
// The method return an HTMLCollection object.
const headers = document.getElementsByClassName("header");

The above method returns the references to both the div tags as an HTMLCollection object which is an array-like object but not an array.

So to convert this HTMLCollection object to an array, we can use the Array.from() method and pass the HTMLCollection object as an argument to the method.

It can be done like this,

// Get all the references to the elements with classname 'header'.
// The method return an HTMLCollection object.
const headers = document.getElementsByClassName("header");

// Convert HTMLCollection object to array
// using the Array.from() method
const headersArr = Array.from(headers);

console.log(headersArr); // [div.header, div.header]

Now if we log the output of the headersArr using the console.log() method we can see that the HTMLCollection object is now converted to an Array in JavaScirpt 🎉.

Now we can use all the native array methods in JavaScirpt like map(), forEach(), find(), filter(), etc.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter