Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript DOM childNodes.length also returning number of text nodes

Tags:

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> 
like image 700
Samuel Liew Avatar asked Jun 15 '11 07:06

Samuel Liew


People also ask

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.

Which of the following properties returns a collection of a nodes child nodes as a NodeList?

The HTML DOM childNodes property returns a collection of node's child nodes in the form of a NodeList object.

What is element childNodes?

Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.


1 Answers

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.)

like image 170
mgiuca Avatar answered Oct 13 '22 11:10

mgiuca