HTMLCollection item() Method
Example
Get the HTML content of the first <p> element of this document:
function myFunction() {
var x = document.getElementsByTagName("P").item(0);
alert(x.innerHTML);
}
Try it Yourself »
Definition and Usage
The item()
method returns the element at the specified index in an
HTMLCollection.
The Elements are sorted as they appear in the source code, and the index starts at 0.
A shorthand method can also be used, and will produce the same result:
var x = document.getElementsByTagName("P")[0];
Try it
Browser Support
Method | |||||
---|---|---|---|---|---|
item() | Yes | Yes | Yes | Yes | Yes |
Syntax
HTMLCollection.item(index)
OR:
HTMLCollection[index]
Parameter Values
Parameter | Type | Description |
---|---|---|
index | Number | Required. The index of the element you want to return. Note: The index starts at 0 |
Return Value
An Element object, representing the element at the specified index.
Returns null if the index number is out of range
More Examples
Example
Change the HTML content of the first <p> element:
document.getElementsByTagName("P").item(0).innerHTML = "Paragraph changed";
Try it Yourself »
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";
}
Try it Yourself »
Example
Get the HTML content of the first <p> element inside a <div> element:
var div = document.getElementById("myDIV");
var x = div.getElementsByTagName("P").item(0).innerHTML;
Try it Yourself »
Related Pages
HTMLCollection: length Property
HTML Element: getElementsByClassName() Method
HTML Element: getElementsByTagName() Method