Javascript DOM HTML HTMLCollection item() Method get inside <div> element

Introduction

Get the HTML content of the first <p> element inside a <div> element:

Click the button to get the content of a P element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {//from   w w w  .j av a  2s  . co m
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>
<p>Use the item() method to get the first P element inside a DIV.</p>

<div id="myDIV">
  <p>First p element in div.</p>
  <p>Another p element in div.</p>
  <p>A third p element in div.</p>
</div>
<button onclick="myFunction()">Get Content</button>

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

<script>
function myFunction() {
  var div = document.getElementById("myDIV");
  var x = div.getElementsByTagName("P").item(0).innerHTML;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related