DOM Collections


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:-
<!DOCTYPE html>
<html>
<body>

<h2>HTML DOM</h2>

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p id="result"></p>

<script>
var myCollect = document.getElementsByTagName("p");
document.getElementById("result").innerHTML =
"The innerHTML of the second paragraph is: " +
myCollect[1].innerHTML;
</script>

</body>
</html> 

Output :-

Note:- The index starts at 0


HTMLCollection Length

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

Example 1 :-
Input:-
<!DOCTYPE html>
<html>
<body>

<h2>HTML DOM</h2>

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p id="result"></p>
<script>
var myCollect = document.getElementsByTagName("p");
document.getElementById("result").innerHTML = 
"This document contains " + myCollect.length + " paragraphs.";
</script>

</body>
</html> 

Output :-

Below is the explanation for above example:-

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

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

Example 2 :-
Input:-
<!DOCTYPE html>
<html>
<body>

<h2>HTML DOM</h2>

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p>Click the button to change the color of all p paragraph.</p>

<button onclick="myFunc()">Click me</button>

<script>
function myFunc() {
  var myCollect = document.getElementsByTagName("p");
  var i;
  for (i = 0; i < myCollect.length; i++) {
    myCollect[i].style.background = "grey";
    myCollect[i].style.color = "white";
  }
}
</script>

</body>
</html> 

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.