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.