Reputation: 921
Nodes are 'automagically' added to elements by Chrome. More experienced front end devs probably deal with this frequently.
It was surprising for me to find in Chrome that the nested div e2 <div id="e1"><div id="e2"></div></div>
has NodeList []
well ok, that is expected, but div e1 has
NodeList(3) [text, div#e2, text]
!!
So an empty div has no child nodes while the outer of two nested divs has 3 child nodes. I can see that text could be added between the divs, so the two text nodes maybe act as placeholders.
But I'm wondering where can I find documentation for this behaviour? What's it called anyway?
And by the same auto add logic shouldn't the inner div have a placeholder text node too??
Upvotes: 0
Views: 46
Reputation: 207527
It is how the method treats whitespace.
childNodes: includes all child nodes—including non-element nodes like text and comment nodes.
const test = elem => console.log(elem.id, elem.childNodes.length, elem.children.length);
test(document.querySelector("#test1"));
test(document.querySelector("#test2"));
test(document.querySelector("#test3"));
test(document.querySelector("#test4"));
<div id="test1"></div>
<div id="test2"> </div>
<div id="test3"><div></div></div>
<div id="test4">
<div></div>
</div>
Upvotes: 1