An HTMLCollection is an array-like object (but not an array)
representing a collection of HTML elements. Methods like
getElementsByTagName() and getElementsByClassName() return this
object.
You can access elements in an HTMLCollection by their index number (starting at 0), just like an array.
const collection = document.getElementsByTagName("p");
// Access the first element
let firstPara = collection[0];
// Access the third element
let thirdPara = collection[2];
The length property defines the number of elements in an
HTMLCollection. Use it to loop through all elements in the collection.
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
An HTMLCollection may look like an array, but it is NOT an array. Here is why:
length property.push(), pop(), or join() on an HTMLCollection
directly.HTMLCollection is "live".
If you add more <p> elements to the document, the collection automatically
updates to include them!
getElementsByTagName and
getElementsByClassName[ ]length property for iterationforEach or `map` support in
older browsersArray.from() if you need array functional
methods