HTML Collection Object


JavaScript HTML DOM Collection

This chapter introduces the use of DOM collections.


HTML Collection object

The getElementsByTagName() method returns an HTMLCollection object.

The HTMLCollection object is like an array containing HTML elements.

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

Example

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

The elements in the collection can be accessed by index (starting at 0).

Access to the second <p> element can be the following code:

y = x[1];

Try It! 


HTML Collection object length property

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

Example

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

 Try It! 

Example analysis

Get the collection of <p> elements:

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

Display the number of collection elements:

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

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

Example

Modify 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! 

Notice

HTMLCollection is not an array!

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

You can use index to get elements like an array.

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