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

Estimated read time 1 min read

There are different ways to convert an HTML Collection to an Array in JavaScript, but one of the most common ones is using the Array.from() method. Here’s an example:

const htmlCollection = document.getElementsByTagName('p'); // Get an HTML collection of all paragraphs
const myArray = Array.from(htmlCollection); // Convert the HTML collection to an array

Alternatively, you can use the spread operator (...) to convert the HTML Collection to an array:

const htmlCollection = document.getElementsByTagName('p'); // Get an HTML collection of all paragraphs
const myArray = [...htmlCollection]; // Convert the HTML collection to an array

Both of these methods create a new array with the same elements as the original HTML collection.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply