Array.prototype.slice
One way to convert an HTMLCollection to a JavaScript array is to use the slice
method.
For instance, if we have several elements:
<div>
foo
</div>
<div>
bar
</div>
<div>
baz
</div>
Then we can select them all and convert the HTMLCollection with the selected elements to an array by writing:
const divs = document.querySelectorAll('div')
const arr = Array.prototype.slice.call(divs)
console.log(arr)
We get divs
by call querySelector
to select all the divs in the HTML.
We just call slice
with divs
and it’ll return the div element objects in an array.
We can also shorten it to:
const divs = document.querySelectorAll('div')
const arr = [].slice.call(divs)
console.log(arr)
We call slice
on an empty array and pass in the divs
HTML.
This does the same thing slice slice
returns a new array.
Array.from
We can use the Array.from
method to convert an array-like or iterable object to an array.
Since an HTMLCollection is an iterable object, we can pass it into the Array.from
method.
For instance, we can write:
const divs = document.querySelectorAll('div')
const arr = Array.from(divs)
console.log(arr)
We pass in divs
straight into Array.from
and it’ll return an array with the div element objects.
Spread Operator
The spread operator also lets us convert an iterable object into an array.
So we can do the same thing by writing:
const divs = document.querySelectorAll('div')
const arr = [...divs]
console.log(arr)
Array.prototype.push and the Spread Operator
We can also use the push
method with the spread operator to push element objects in an HTMLCollection into an array.
For instance, we can write:
const divs = document.querySelectorAll('div')
const arr = []
arr.push(...divs)
console.log(arr)
Then we spread the items in divs
arguments of push
.
And then they’ll all be pushed to arr
.
Array.prototype.concat and the Spread Operator
The concat
array method also lets us append items to an array by passing them into the method as arguments.
Therefore, we can use them like push
to add items into the array.
For instance, we can write:
const divs = document.querySelectorAll('div')
const arr = [].concat(...divs)
console.log(arr)
Then concat
returns a new array with the divs
added to the empty array that it’s called on.
So arr
has the same value as the previous examples.