Easy Tutorial
❮ Home Prop Search Maxlength ❯

HTMLCollection item() Method

DOM HTMLCollection


Definition and Usage

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

The order of elements in the HTMLCollection object is the same as they appear in the document source code, with the index starting at 0.

You can also use the following shorthand, which yields the same result:

var x = document.getElementsByTagName("P")[0];

Syntax

HTMLCollection.item(index)

or:

HTMLCollection[index]
Parameter Type Description
index Number Required. The index of the element. <br> <br> Note: The starting position is 0, and the index of the last element is HTMLCollection.length-1, which must be within this range.

Browser Support

Method
item() Yes Yes Yes Yes Yes

Examples

Modify the HTML content of the first p element:

document.getElementsByTagName("P").item(0).innerHTML = "Paragraph modified";

Example

Loop through all elements with class="myclass" and change their background color:

var x = document.getElementsByClassName("myclass");

for (i = 0; i < x.length; i++) {
  x.item(i).style.backgroundColor = "red";
}

Example

Get the HTML content of the first p element and insert it into a div element:

var div = document.getElementById("myDIV");
var x = div.getElementsByTagName("P").item(0).innerHTML;

Related Articles

HTMLCollection: length Property

HTML Element: getElementsByClassName() Method

HTML Element: getElementsByTagName() Method


DOM HTMLCollection

❮ Home Prop Search Maxlength ❯