skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search