HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Collections

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.


Accessing the Collection

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

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";
}

HTMLCollection vs. Array

An HTMLCollection may look like an array, but it is NOT an array. Here is why:

  • Index: Both use indices (0, 1, 2...).
  • Length: Both have a length property.
  • Methods: You cannot use array methods like push(), pop(), or join() on an HTMLCollection directly.
Technical Detail: An HTMLCollection is "live". If you add more <p> elements to the document, the collection automatically updates to include them!

Key Points to Remember

  • HTMLCollection is a list of HTML elements
  • It is returned by getElementsByTagName and getElementsByClassName
  • Access individual items using square brackets [ ]
  • Use the length property for iteration
  • It is not a real array, so no forEach or `map` support in older browsers
  • Always convert to an array using Array.from() if you need array functional methods
  • An HTMLCollection is live and reflects real-time DOM changes