Javascript DOM HTML NodeList item() Method

Introduction

Get the HTML content of the first <p> element (index 0) inside the document:

var nodelist = document.getElementsByTagName("P").item(0).innerHTML;

Click the button to get the HTML content of the first p element (index 0) in this document.

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>The first p element in the document.</p>
<p>Another p element.</p>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {// w w  w  . ja  v  a2 s. c o  m
  var nodelist = document.getElementsByTagName("P").item(0).innerHTML;
  document.getElementById("demo").innerHTML = nodelist;
}
</script>

</body>
</html>

The item() method returns a node by index in a NodeList object.

The nodes are sorted as they appear in the source code, and the index starts at 0.

A Node object's collection of child nodes is a NodeList object.

There are two ways to access a node at the specified index in a node list:

document.body.childNodes.item(0);??? // The first child node of <body>
document.body.childNodes[0];?????? ? // The first child node of <body>

Click the button to change the HTML content of the body element's first child node (index 0).

View in separate window

<!DOCTYPE html>
<html>
<body><p>This is the first p element in body.</p>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/*from   w ww.ja v a2 s  .  c om*/
  document.body.childNodes.item(0).innerHTML = "Changed!";
}
</script>

</body>
</html>

The code above will produce the same result as the following code.

Click the button to change the HTML content of the body element's first child node (index 0).

View in separate window

<!DOCTYPE html>
<html>
<body><p>This is the first p element in body.</p>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/*from ww  w . jav  a  2s. c om*/
  document.body.childNodes[0].innerHTML = "Changed!";
}
</script>

</body>
</html>

We can use the length property to return the number of nodes in a NodeList object.

item(number)

Parameter Values

Parameter Type Description
index Number Required. The index of the node. index starts at 0.

The item() method returns a Node object representing the node at the specified index.

The item() method returns null if the index number is out of range.




PreviousNext

Related