Wael Showair
Wael Showair

Reputation: 3102

Missing children nodes within DOM

I am using DOM to retrieve children of my element node whose class name is 'main' as indicated in the html snippet below. It seems to me that there 9 children elements under the parent element. but i was surprised by the children nodes values. Does anyone has an explanation for the output below

<section class="main">
 <h2>Page Title</h2>
 <h3>Article Heading</h3>
 <p>First Paragraph</p>
 <p>Second Paragraph</p>
 <p>Third Paragraph</p>
 <p>Fourth Paragraph</p>
 <h3>Instructions</h3>
 <p>Fifth Paragraph</p>
 <p>Sixth Paragraph</p>
</section>

JS code:

var articleHeadElemNode = document.querySelector(".main");
console.log(articleHeadElemNode.childElementCount);

for (i =0; i<articleHeadElemNode.childElementCount ; i++ )
  console.log(articleHeadElemNode.childNodes[i]);

Final Output:

9
#text
<h2>​Page Title​</h2>​
#text
<h3>​Article Heading​</h3>​
#text
<p>​First Paragraph​</p>​
#text
<p>​Second Paragraph​</p>​
#text

Where are the rest of paragraphs? I managed to retrieve the elements using document.querySelector(".main > h3") or using querySelectorAll but I am interested in logical explanation for what is going on here?

Upvotes: 2

Views: 904

Answers (2)

Daryl Ginn
Daryl Ginn

Reputation: 1424

You're best off using Element.children for child elements. Element.children returns only element node children, while Node.childNodes will return all node children:

for(var i = 0; i < articleHeadElemNode.childElementCount; i++)
  console.log(articleHeadElemNode.children[i]);

Working Fiddle.

Upvotes: 1

Ram
Ram

Reputation: 144739

That's because you are reading childElementCount which is count of childNodes that have nodeType of 1 and you are reading all the childNodes in the loop which also returns the textNodes that have nodeType of 3. You should use the children property in the loop instead of the childNodes.

Upvotes: 1

Related Questions