Javascript DOM HTML Node childNodes Property get child nodes of <div>

Introduction

Find out how many child nodes a <div> element has:

var c = document.getElementById("myDIV").childNodes.length;

Click the button to find out how many child nodes the div element below has.

Whitespace inside elements is considered as text, and text is considered as nodes. In this example, index 0, 2 and 4 in DIV are text nodes.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/*from  w w w.  ja v  a  2  s.c o m*/
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>

<div id="myDIV">
  <p>First p element (index 1)</p>
  <p>Second p element (index 3)</p>
</div>
<p id="demo"></p>

<script>
function myFunction() {
  var c = document.getElementById("myDIV").childNodes.length;
  document.getElementById("demo").innerHTML = c;
}
</script>

</body>
</html>



PreviousNext

Related