JavaScript DOM childNodes.length 也返回文本节点的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6354590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript DOM childNodes.length also returning number of text nodes
提问by Samuel Liew
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?
在 JavaScript DOM 中, childNodes.length 返回元素和文本节点的数量。有没有办法只计算纯元素子节点的数量?
For example, childNodes.length
of div#posts
will return 6, when I expected 2:
例如,当我期望 2 时,childNodes.length
ofdiv#posts
将返回 6:
<div id="posts">
<!-- some comment -->
<!-- another comment -->
<div>an element node</div>
<!-- another comment -->
<span>an element node</span>
a text node
</div>
回答by mgiuca
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.)
最好的办法是迭代 childNodes 数组并只计算那些带有nodeType == Node.ELEMENT_NODE
. (并编写一个函数来这样做。)
回答by Felix Kling
You could use Element.children
, but IE (up to 8) seems to consider comment nodestoo.
您可以使用Element.children
,但 IE(最多 8 个)似乎也考虑评论节点。
回答by ConnorsFan
You can use document.querySelectorAll('#posts > *')
:
您可以使用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>
回答by andyb
You could filter by Node.nodeType(Mozilla's documentation because I think it's a great resource).
您可以按Node.nodeType(Mozilla 的文档,因为我认为这是一个很好的资源)进行过滤。