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 length Property returns the number of elements in the collection.
The elements can be accessed by index (starts at 0).
An HTMLCollection is live. It is automatically updated when the document is changed.
See Also
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 |
Element | The 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 |