With this HTML:
<p id="child"><span id="grandchild"></span></p>
And this JavaScript:
var x = document.getElementById("child").childNodes;
console.log(x.length);
I get 1. With this HTML instead:
<p id="child"><span id="grandchild">hi</span></p>
I get 1 as well. I was expecting 2.
In the first HTML snippet, I expected 1 because of the span element. In the second snippet, I was expecting 2 because there’s not just the span element, but also the hi text node.
What am I misunderstanding?
Child nodes refers only to the direct nodes under.
If you want to countall the descendants you have to do it recursively, please see below sample: