HTML DOM NodeList item() Method
- Previous page forEach()
- Next page keys()
- Go back to the previous level HTML DOM NodeList
Definition and Usage
item()
The method returns the node at the specified index in the NodeList.
There are two ways to access the node at a specified index:
list.item(index)
or
list[index]
The simplest and most commonly used method is [index].
Instance
Example 1
Get the child nodes of the <body> element:
const nodeList = document.body.childNodes;
Example 2
Get the node name of the first child node:
const list = document.body.childNodes; let name = list.item(0).nodeName;
Example 3
The result of this example is the same:
const list = document.body.childNodes; let name = list[0].nodeName;
Example 4
Get the HTML content of the first <p> element in the document:
const list = document.getElementsByTagName("p"); let text = list.item(0).innerHTML;
Example 5
Get the HTML content of the first <p> element in "myDIV":
const div = document.getElementById("myDIV"); const list = div.getElementsByTagName("p"); let text = list[0].innerHTML;
Example 6
Change the HTML content of the first <p> element in "myDIV":
const div = document.getElementById("myDIV"); const list = div.getElementsByTagName("p"); let text = list[0].innerHTML = "Paragraph changed";
Example 7
Change the color of all elements with class="child":
const list = document.querySelectorAll(".child"); for (let i = 0; i < list.length; i++) { list[i].style.color = "red"; }
Syntax
nodelist.item(index)
or abbreviated as:
nodelist[index]
Parameter
Parameter | Description |
---|---|
index |
Required. The index (subscript) of the node in the list. Nodes are sorted in the order they appear in the document. The index starts from 0. |
Return value
Type | Description |
---|---|
Object | The node at the specified index. |
null | If the index is out of range. |
Browser support
nodelist.item() is a DOM Level 1 (1998) feature.
All modern browsers support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
Related pages
- Previous page forEach()
- Next page keys()
- Go back to the previous level HTML DOM NodeList