JavaScript Tutorial

DOM Collections

DOM Collections are similar to Node Lists in that they represent collections of DOM nodes. However, there are some differences between them.

A DOM Collection is a generic term used to describe any collection of DOM nodes. It can refer to various types of collections in the DOM, such as the HTMLCollection or the NodeList.

HTMLCollection Object

The getElementsByTagName() method returns an HTMLCollection object.

An HTMLCollection object is similar to an array list (collection) of HTML elements.

The below code selects all <p> elements in a document:

Example :-

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

The elements in the HTML collection can be accessed or get by an index number.

For example, to access the second <p> element user can use:

var secondElem = elem[1];

Input:-

Output :-

Note:- The index starts at 0

HTMLCollection Length

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

Example 1 :-

Input:-

Output :-

Below is the explanation for the above example:-

  1. Create a collection of all <p> elements
  2. Display the length of the collection

The length property is also useful when the user wants to loop through the elements in a collection:

Example 2 :-

Input:-

Output (Before Click):-

Output (After Click):-

Note:-

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.

Go back to Previous Course