JavaScript DOM childNodes.length also returning number of text nodes


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>

Not directly. Text nodes (including comments and so on) are child nodes.

Your best bet is to iterate over the childNodes array and count up only those nodes with nodeType == Node.ELEMENT_NODE. (And write a function to do so.)


You could use Element.children, but IE (up to 8) seems to consider comment nodes too.


You could filter by Node.nodeType (Mozilla's documentation because I think it's a great resource).


You can use document.querySelectorAll('#posts > *'):

var children = document.querySelectorAll('#posts > *');
console.log('Number of children: ' + children.length);
<div id="posts">
    <!-- some comment -->
    <!-- another comment -->
    <div>an element node
        <span>a grand-child node</span>
    </div>
    <!-- another comment -->
    <span>an element node</span>
    a text node
</div>


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.