JavaScript DOM childNodes.length also returning number of text nodes

Viewed 22983

In JavaScript DOM, childNodes.length returns the number of both element and text nodes. Is there any way to count only the number of element-only child nodes?

For example, childNodes.length of div#posts will return 6, when I expected 2:

<div id="posts">
    <!-- some comment -->
    <!-- another comment -->
    <div>an element node</div>
    <!-- another comment -->
    <span>an element node</span>
    a text node
</div>
5 Answers

Envoking element.childNodes will return a NodeList which DOES contain contain text and other ancillary items, where as envoking element.children will return an HTMLCollection object which DOES NOT contain text and other ancillary items.

If you must use childNodes, then you must understand that there is a difference between looping through the resulting NodeList using

for(i in nodelist)

vs

for(i = 0 ; i < nodelist.length ; i++)

The first method will also retrieve text and other ancillary items.

Related