Search code examples
javascriptdomhtml-parsingdocument-bodychild-nodes

Number of child Nodes on Body element javascript


The number of child nodes on Body element is 1 even though there is nothing there. This happens only with Body element, but not for other elements, such as div for example. In that case the result is 0. Why is that?

<head>
<script>
  function run() {
    alert(document.body.childNodes.length);
  }
  window.addEventListener("load", run, false);
</script>
</head>

<body></body>

</html>

while the result of this is 0

<!Doctype html>
<html>
<head>
<script>
  function run() {
    alert(document.body.getElementsByTagName("div")[0].childNodes.length);
  }
   window.addEventListener("load",run,false);
</script>
</head>
<body>
<div></div>
</body>
</html>

Solution

  • Due to requirements of the HTML parsing algorithm, in the DOM that body in the code snippet in the question ends up containing two line breaks. So it does have a text node child in the DOM.

    Try document.documentElement.innerHTML with that doc—e.g., just modify the code snippet like:

    <head>
    <script>
      function run() {
        alert(document.body.childNodes.length);
        alert(document.documentElement.innerHTML);
      }
      window.addEventListener("load", run, false);
    </script>
    </head>
    
    <body></body>
    
    </html>
    

    …and what you will get back is this:

    <head>
    <script>
      function run() {
        alert(document.body.childNodes.length);
        alert(document.documentElement.innerHTML);
      }
      window.addEventListener("load", run, false);
    </script>
    </head>
    
    <body>
    
    
    </body>
    

    Or just inspect the document in the question in browser devtools or using Live DOM Viewer.