Javascript DOM HTML HTMLCollection item() Method

Introduction

Get the HTML content of the first <p> element of this document:

The item() method returns the element at the specified index.

Click the button to return the content of the first P element:

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Alert innerHTML of P</button>
<p id="demo"></p>
<script>
function myFunction() {/*  w  w w  .  jav a2 s . com*/
  var x = document.getElementsByTagName("P");
  document.getElementById("demo").innerHTML = x.item(0).innerHTML;
}
</script>

</body>
</html>

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.

item(index);

Parameter Values

Parameter Type Description
index Number Required. The index of the element to get. The index starts at 0

The item() method returns an Element object representing the element at the specified index.

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

A shorthand method can also be used, and will produce the same result:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>This is the first p element in body.</p>
<p>This example uses a shorthand method for the item() method</p>
<button onclick="myFunction()">Change Content</button>

<script>
function myFunction() {/*www .  j  a v a  2s.c o  m*/
  var x = document.getElementsByTagName("P")[0];
  x.innerHTML = "Changed!";
}
</script>

</body>
</html>



PreviousNext

Related