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

Introduction

Get a collection of the <body> element's child nodes:

var c = document.body.childNodes;

Click the button get info about the body element's child nodes.

Whitespace inside elements is considered as text, and text is considered as nodes. Comments are also considered as nodes.

View in separate window

<!DOCTYPE html>
<html>
<body><!-- This is a comment node! -->
<button onclick="myFunction()">Test</button>
test test/*from   ww w  .  j  a  v  a 2s.c o m*/

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

<script>
function myFunction() {
  var c = document.body.childNodes;
  var txt = "";
  var i;
  for (i = 0; i < c.length; i++) {
    txt = txt + c[i].nodeName + "<br>";
  }

  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

The childNodes property returns a collection of a node's child nodes, as a NodeList object.

The nodes in the collection are sorted as they appear in the source code.

The nodes can be accessed by index numbers. The index starts at 0.

Whitespace inside elements is considered as text, and text is considered as nodes.

Comments are also considered as nodes.

This property is read-only.

To return a collection of a node's element nodes excluding text and comment nodes, use the children property.

element.childNodes[0] will produce the same result as the firstChild property.




PreviousNext

Related