I have a section element having 3 div parent elements, I want to log section children.
<section class="section1">
<div class="parent">
<p class="childP">hello</p>
</div>
<div class="parent">
<p class="childP">bro
</div>
<div class="parent-3">
<p class="childP">bro
</div>
</section>
const section = document.querySelector('.section1');
when I log, console.log(section.childNodes);
the output is NodeList(7) [text, div.parent, text, div.parent, text, div.parent-3, text]
What is this Extra text in node list ?
I tried console.log(section.children)
is woking completely fine giving output in Element Nodes i.e HTMLcollection, I need the reason for extra text in section.childNodes
node list?
2
Answers
It is for the whitespace between each of the child
<div>
elements. Here is the markup with the whitespace removed, and thus noText
nodes are present in.childNodes
.childNodes
will return anyelement
ortext
orcomment
nodes whose direct children of the target element.So, the question is where do the text nodes come from?!
The new lines between the
div
s element is considered as a text node.If, you remove the new lines, there will be no text nodes.