There are three ways to convert an HTML Collection into an array in JavaScript.
You can convert an HTML collection into an array in JavaScript using Array.from() method.
This tutorial teaches you how to convert an HTML collection into an array in JavaScript using different methods.
HTML Collection
The following code demonstrates creating 4
paragraphs with the HTML
class name para
.
You can get this as a collection for converting them into an array.
<p class="head">Paragraphs are</p>
<p class="para">p1</p>
<p class="para">p2</p>
<p class="para">p3</p>
<p class="para">p4</p>
Output
The following text is rendered when the HTML code is executed.
Paragraphs are
p1
p2
p3
p4
You’ll learn the different methods to convert the HTML collection into an Array.
Using Array From
The array.from()
static method creates a new shallow copied array from any type of collection/iterable.
To create an array from the HTML collection, pass the collections to the array.from()
method.
- It’ll return a new array based on the elements in the collection.
It also supports a map function. You can use this if you want to apply a function to each element in the collection before pushing it into an array. For example, convert the text of the element into upper case.
Code
const paraCollection = document.getElementsByClassName("para");
const paraArray = Array.from(paraCollection);
paraArray.forEach(element => console.log(element.textContent));
Output
"p1”
"p2"
"p3"
"p4"
Using Spread Operator
The spread operator [...]
expands an iterable where zero or more arguments are expected.
Using the spread operator, you can expand the HTML collection into a JavaScript operator.
Use this method when you want to convert an HTML collection into an array and add some additional elements to the array. (Optional).
Code
The following code demonstrates adding the HTML collection with class para and an additional element with class name head.
const paraArray = [document.getElementsByClassName("head")[0], ...document.getElementsByClassName('para')];
paraArray.forEach(element => console.log(element.textContent));
Output
"p1”
"p2"
"p3"
"p4"
Using Array Slice Call
The call()
method allows you to set the value of the this
args.
When you invoke the call() method along with slice(), you pass the HTML collection as the this
arg in the slice()
function.
Use this method when you want to create an array with elements starting from a specific position instead of a complete array.
Code
The following code demonstrates how to use the slice.call()
method to create an array with elements from starting index 1
.
const paraArray = Array.prototype.slice.call(document.getElementsByClassName('para'),1);
paraArray.forEach(element => console.log(element.textContent));
Output
"p2"
"p3"
"p4"