JavaScript HTML DOM Collections
This section introduces the use of DOM collections.
HTMLCollection Object
The getElementsByTagName()
method returns an HTMLCollection object.
The HTMLCollection object is an array-like collection of HTML elements.
The following code retrieves all <p>
elements in the document:
Example
var x = document.getElementsByTagName("p");
Elements in the collection can be accessed by their index (starting from 0).
To access the second <p>
element, you can use the following code:
y = x[1];
HTMLCollection 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;
Example Analysis
Retrieve 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 length
property is often used to iterate through 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";
}
Note
HTMLCollection is not an array!
An HTMLCollection may look like an array, but it is not.
You can access elements using their index like an array.
HTMLCollection cannot use array methods such as valueOf()
, pop()
, push()
, or join()
.