HTMLCollection item()

Example

Get the HTML content of the first <p> element:

const collection = document.getElementsByTagName("p").item(0);
let text = collection.innerHTML;
Try it Yourself »

This shorthand produces the same result:

const collection = document.getElementsByTagName("p")[0];
let text = collection.innerHTML;
Try it Yourself »

Change the HTML content of the first <p> element:

document.getElementsByTagName("p")[0].innerHTML = "Paragraph changed";
Try it Yourself »

More examples below.


Description

The item() method returns the element at a specified index in an HTMLCollection.


HTMLCollection

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

The elements in a collection can be accessed by index (starts at 0).

The length Property returns the number of elements in the collection.



Syntax

HTMLCollection.item(index)
or
HTMLCollection[index]

Parameters

Parameter Description
index Required.
The index of the element to return.
The index starts at 0.

Return Value

Type Description
ElementThe element at the specified index.
null if the index is out of range.


More Examples

Example

Loop over all elements with class="myclass", and change their font size:

const collection = document.getElementsByClassName("myclass");

for (let i = 0; i < collection.length; i++) {
  collection.item(i).style.fontSize ="24px";
}
Try it Yourself »

Example

Get the content of the second <p> element inside "myDIV":

const div = document.getElementById("myDIV");
const collection = div.getElementsByTagName("p");
let text = collection[1].innerHTML;
Try it Yourself »

Browser Support

HTMLCollection.item() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.