The getElementsByTagName() method returns an HTMLCollection object, which is an array-like list of HTML elements.
The following code selects all <p> elements in the document:
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 begins at 0.
The length property specifies the number of elements in an HTMLCollection.
myCollection.length |
The length property is helpful when you need to iterate through the elements in a collection.
Modify 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! Although an HTMLCollection behaves similarly to an array, it is not actually an array. You can loop through the collection and access elements using an index (just like an array). However, array methods such as valueOf(), pop(), push(), or join() cannot be used on an HTMLCollection. |