Extra text node in nodelist?

184 views Asked by At

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

There are 2 answers

0
Wongjn On BEST ANSWER

It is for the whitespace between each of the child <div> elements. Here is the markup with the whitespace removed, and thus no Text nodes are present in .childNodes.

console.log(document.querySelector('.section1').childNodes)
<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>

0
Mina On

childNodes will return any element or text or comment nodes whose direct children of the target element.

So, the question is where do the text nodes come from?!

The new lines between the divs element is considered as a text node.

If, you remove the new lines, there will be no text nodes.

console.log([...document.querySelector('.section1').childNodes].map(e => e.nodeName))
<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>