Mankament Gra Mankament Gra - 10 months ago 45
Javascript Question

How many child node i have in body

I have code HTML i i have problem with this:

<html><head></head><body><!--oneComment--><script src="index.js"></script><!--twoComment--></body></html>

And i Have javascript code in index.js:

console.log(document.body.childNodes.length) //2

When i run this code in firefox in console a get 2, why? i have two comment and one script element in body. Two commend and one script is 3 node, so why i get log 2

Answer Source

Your script is before the second comment in the DOM. Therefore the second comment doesn't exist yet when your script runs and you are left with only two childNodes: the first comment and the script.

Compare your result to the output of:

window.onload = function ( ) {