HTMLCollection item()Methods
Definition and Usage
The item() method returns the element at the specified index position in the HTMLCollection object.
The order of elements in the HTMLCollection object is the same as their order in the document source code, with the index starting at 0.
You can also use the following shorthand method, and the result will be the same:
var x = document.getElementsByTagName("P")[0];
Syntax
HTMLCollection.item(index)
Or:
HTMLCollection[index]
| Parameter | Type | Description |
|---|---|---|
| index | Number | Required, the index value of the element. Note:The starting position is 0, and the index of the last element is HTMLCollection.length-1; the index must be within this range. |
Browser Support
| Methods | |||||
|---|---|---|---|---|---|
| item() | Yes | Yes | Yes | Yes | Yes |
Example
Example
Modify the HTML content of the first p element:
document.getElementsByTagName("P").item(0).innerHTML = "Paragraph modified";
Try it Yourself »
Example
Loop through all elements with class="myclass" and modify their background color:
var x = document.getElementsByClassName("myclass");
for (i = 0; i < x.length; i++) {
x.item(i).style.backgroundColor = "red";
}
Try it Yourself »
Example
Get the HTML content of the first p element and insert it into the div element:
var div = document.getElementById("myDIV");
var x = div.getElementsByTagName("P").item(0).innerHTML;
Try it Yourself »
Related Articles
HTMLCollection: lengthProperty
HTML Element: getElementsByClassName()Methods
HTML Element: getElementsByTagName()Methods
other extensions