Search code examples
javascripthtmlnodelisthtmlcollectionchild-nodes

Extra text node in nodelist?


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?


Solution

  • 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>