Javascript DOM HTML NodeList length Property get children's node name

Introduction

Loop through the child nodes of <body> and output the node name of each child node:

Click the button get the node names of the body element's child nodes.

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

View in separate window

<!DOCTYPE html>
<html>
<body><!-- This is a comment node! -->

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

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

<script>
function myFunction() {/*  w ww . j  a v  a 2s .c  o  m*/
  var nodelist = document.body.childNodes;

  var txt = "";
  var i;
  for (i = 0; i < nodelist.length; i++) {
    txt = txt + nodelist[i].nodeName + "<br>";
  }

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

</body>
</html>



PreviousNext

Related