DEV Community

Cover image for How to convert an HTMLCollection object to an Array in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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]
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 😃.


Discussion (0)