---
title: DOM Collections
description: "## The HTMLCollection Object The `getElementsByTagName()` method returns an `HTMLCollection` object. An `HTMLCollection` object is an array-like list (collection) of HTML elements. The following code selects all `` elements in a document: ### Example `var x = document.getElementsByTagName(\"p\");` The elements in the collection can be accessed by an…"
url: "https://apprentice.mn/docs/dom-collections/"
updated: "2021-05-19"
category: Javascript
---

# DOM Collections

## The HTMLCollection Object

The `getElementsByTagName()` method returns an `HTMLCollection` object.

An `HTMLCollection` object is an array-like list (collection) of HTML elements.

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

### Example

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

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

To access the second <p> element you can write:

     `y = x[1];`

**Note:** The index starts at 0.

---

## HTML HTMLCollection Length

The `length` property defines the number of elements in an `HTMLCollection`:

### Example

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

Example explained:

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

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

### Example

Change the text color of all <p> elements:

      `var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
  myCollection[i].style.color = "red";
}`

**An HTMLCollection is NOT an array!**

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.

        [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fdom-collections%2F&linkname=DOM%20Collections)[https://www.addtoany.com/share](https://www.addtoany.com/share)
