JavaScript HTML DOM Collection

HTMLCollection object

getElementsByTagName() The method returns HTMLCollection Object.

The HTMLCollection object is a list (collection) of HTML elements that is similar to an array.

The following code selects all <p> elements in the document:

Example

var x = document.getElementsByTagName("p");

The elements in the set can be accessed by index number.

To access the second <p> element, you can write it like this:

y = x[1];

Try It Yourself

Note:The index starts from 0.

HTML HTMLCollection length

length The attribute defines the number of elements in the HTMLCollection:

Example

var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length; 

Try It Yourself

Example Explanation:

  • Create a collection of all <p> elements
  • Displays the length of the collection

length Properties are useful when you need to iterate over elements in a collection:

Example

Change the background color of all <p> elements:

var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
    myCollection[i].style.backgroundColor = "red";
}

Try It Yourself

HTMLCollection is not an array!

HTMLCollection may look like an array, but it is not an array.

You can iterate over the list and access elements by numeric reference (like an array).

However, you cannot use array methods on HTMLCollection, such as valueOf(),pop(),push() or join().