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?
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-divchildNodes[1]: the #third-divchildNodes[2]: the line break between the #third-div and the #third-divs-siblingchildNodes[3]: the #third-divs-siblingchildNodes[4]: the line break between the #third-divs-sibling and the closing tagIf you're looking only for elements, you can use the .children collection instead of .childNodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With