How to Use an HTML Collection as an Array in JavaScript?

Estimated read time 2 min read

An HTML Collection is a collection of HTML elements that can be accessed and manipulated using JavaScript. HTML Collections can be treated as arrays, allowing you to use array methods such as forEach or map, or access individual elements using array syntax (e.g., myCollection[0]). However, HTML Collections are not true arrays, so not all array methods are available.

Here’s an example:

<!DOCTYPE html>
      function changeColor() {
        var elements = document.getElementsByTagName("p");
        Array.from(elements).forEach(function(element) {
 = "red";
    <h1>Using an HTML Collection as an Array in JavaScript</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <button onclick="changeColor()">Change Color</button>

In this example, the JavaScript function changeColor is defined and executed when the “Change Color” button is clicked. The function uses document.getElementsByTagName to select all the <p> elements and store them in a variable called elements. The Array.from method is then used to convert the HTML Collection to a true JavaScript array. Finally, the forEach method is used to loop through the array and change the color of each <p> element to red.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply