Categories
JavaScript Answers

How to convert an element collection to an array in JavaScript?

Spread the love

Sometimes, we want to convert an element collection to an array in JavaScript.

In this article, we’ll look at how to convert an element collection to an array in JavaScript.

How to convert an element collection to an array in JavaScript?

To convert an element collection to an array in JavaScript, we can use the spread operator.

For instance, we write:

<div>

</div>
<div>

</div>

Then we write:

const divs = document.getElementsByTagName('div');
const myArray = [...divs];
console.log(myArray)

to select the divs with document.getElementsByTagName.

Then we spread the divs into an array with [...divs].

Now we see that myArray is an array of div elements.

Conclusion

To convert an element collection to an array in JavaScript, we can use the spread operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *