JavaScript DOM Collections
JavaScript Basics

JavaScript DOM Collections

JavaScript HTML DOM Collections

The HTMLCollection Object

The getElementsByTagName() method returns an HTMLCollection object, which is an array-like list (collection) of HTML elements.

Example: Selecting All <p> Elements

const myCollection = document.getElementsByTagName("p");‍
The elements in the collection can be accessed using an index number. To access the second <p> element, you can write:‍
myCollection[1];

Note: The index starts at 0.

HTMLCollection Length

The length property defines the number of elements in an HTMLCollection:

Example:

myCollection.length;

The length property is useful when you want to loop through the elements in a collection:

Example: Changing the Text Color of All <p> Elements
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) 
{  myCollection[i].style.color = "red";}‍

An HTMLCollection is NOT an Array!

An HTMLCollection may look like an array, but it is not. You can loop through the list and refer to the elements with a number, just like an array. However, you cannot use array methods like valueOf(), pop(), push(), or join() on an HTMLCollection.

Take a look into your desired course