How to Convert an HTML Collection to an Iterable Array in JavaScript?

Estimated read time 1 min read

You can convert an HTML Collection to an iterable Array in JavaScript by using the Array.from() method or the spread operator (...).

Here’s an example using Array.from():

var collection = document.getElementsByClassName("myClass");
var array = Array.from(collection);
console.log(array);

In this example, the getElementsByClassName method is used to retrieve a collection of elements with the class “myClass”, and the Array.from() method is used to convert the collection to an Array. The resulting array is stored in the array variable, which can be logged to the console or used elsewhere in your code.

Here’s an example using the spread operator:

var collection = document.getElementsByClassName("myClass");
var array = [...collection];
console.log(array);

In this example, the spread operator is used to spread the elements of the collection into a new Array. The resulting array is stored in the array variable, which can be logged to the console or used elsewhere in your code.

Both of these examples assume that there are elements in the HTML document with the class “myClass”. You should replace this class with the class of the actual elements you want to convert to an array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply