HTMLCollection item() Method
- Previous Page item()
- Next Page length
- Go Back to the Previous Level DOM HTMLCollection
Definition and usage
item()
The method returns the element at the specified index in the HTMLCollection.
Elements are sorted according to their appearance in the source code, with the index starting from 0.
You can also use a shorthand method and get the same result:
var x = document.getElementsByTagName("P")[0];
Example
Example 1
Get the HTML content of the first <p> element in this document:
function myFunction() { var x = document.getElementsByTagName("P").item(0); alert(x.innerHTML); }
Syntax
HTMLCollection.item(index)
or:
HTMLCollection[index]
Parameter value
Parameter | Type | Description |
---|---|---|
index | Number |
Required. The index of the element to be returned. Note:The index starts from 0. |
Return value
Element object, indicating the element at the specified index.
If the index number is out of range, it returns null.
Browser support
Method | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
item() | Support | Support | Support | Support | Support |
More examples
Example 2
Change the HTML content of the first <p> element:
document.getElementsByTagName("P").item(0).innerHTML = "Paragraph changed";
Example 3
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 4
Get the HTML content of the first <p> element within the <div> element:
var div = document.getElementById("myDIV"); var x = div.getElementsByTagName("P").item(0).innerHTML;
Related pages
HTMLCollection:length attribute
HTML Element:The getElementsByClassName() method
HTML Element:getElementsByTagName() Method
- Previous Page item()
- Next Page length
- Go Back to the Previous Level DOM HTMLCollection