Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes childNodes to return #text instead of <div>?

Tags:

javascript

childNodes occasionally gives me #text element instead of <div>

<div class="first-div">
    <div class="second-div">
        <div class="third-div">1</div>
        <div class="third-divs-sibling">2</div>
    </div>
</div>

When I try to access the grandchildren here like this:

var xxx = document.getElementsByClassName('first-div')[0];

console.log(xxx.childNodes[ 1 ].childNodes[ 1 ]);
console.log(xxx.childNodes[ 1 ].childNodes[ 2 ]);

Chrome gives me this:

<div class="third-div">1</div>
#text

Here is JSFiddle

At first, I thought it found white space somewhere, but console.log(xxx.childNodes[ 1 ]) returns only 3 nodes. It looks like foul magic to my untrained eye.

Does anyone have a more scientific explanation?

like image 864
Arthur Tarasov Avatar asked Oct 26 '25 03:10

Arthur Tarasov


1 Answers

Whitespace creates text nodes as well. Your #second-div has in fact 5 children of which only 2 are elements:

  • childNodes[0]: the line break between the opening tag and the #third-div
  • childNodes[1]: the #third-div
  • childNodes[2]: the line break between the #third-div and the #third-divs-sibling
  • childNodes[3]: the #third-divs-sibling
  • childNodes[4]: the line break between the #third-divs-sibling and the closing tag

If you're looking only for elements, you can use the .children collection instead of .childNodes.

like image 168
Bergi Avatar answered Oct 28 '25 15:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!