JavaScript HTML DOM Collection

This chapter introduces the use of DOM collections.


HTMLCollection Object

The getElementsByTagName() method returnsHTMLCollectionan object.

The HTMLCollection object is similar to an array that contains HTML elements.

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

Examples

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

Elements in a collection can be accessed by index (starting at 0).

To access the second <p> element, you can use the following code:

y = x[1];

Try it Yourself »

HTMLCollection Object length Property

The length property of the HTMLCollection object defines the number of elements in the collection.

Examples

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

Try it Yourself »

Example Analysis

Get the collection of <p> elements:

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

Display the number of elements in the collection:

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

The collection's length property is often used to traverse the elements in a collection.

Examples

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 »

Note

HTMLCollection is not an array!

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

You can use indexes to get elements just like an array.

HTMLCollection cannot use array methods: valueOf(), pop(), push(), or join().

Other Extensions