Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  60] [ 3]  / answers: 1 / hits: 24338  / 13 Years ago, wed, june 15, 2011, 12:00:00

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>

More From » html

 Answers
18

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


[#91702] Tuesday, June 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaya

Total Points: 531
Total Questions: 107
Total Answers: 100

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;