Open Playground
JS HTML DOMLesson #268

JavaScript HTML DOM Collections

The getElementsByTagName() method returns an HTMLCollection object.

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

Example Code

javascript
Try it Yourself
const myCollection = document.getElementsByTagName("p");

Note: The index starts at 0.


HTML HTMLCollection Length

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

Example

Example Code

javascript
Try it Yourself
myCollection.length

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

Example

```javascript const myCollection = document.getElementsByTagName("p");

for (let i = 0; i 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.



Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const myCollection = document.getElementsByTagName("p");

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
myCollection.length

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const myCollection = document.getElementsByTagName("p");

for (let i = 0; i < myCollection.length; i++) {

  myCollection[i].style.color = "red";

}