Javascript - 子节点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11776570/
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 - child node count
提问by Karthick V
<ul>
<li>Array1</li>
<li>Array2</li>
<li id="element">Array3</li>
</ul>
<script>
var temp = document.getElementById('element').parentNode;
child = temp.childNodes;
console.log(temp.length);
</script>
I need to get the child node length using element id. My code returns 7 as a result but I have only 3 nodes.
我需要使用元素 id 获取子节点长度。结果我的代码返回 7,但我只有 3 个节点。
回答by Christoph
What you want is .children.length
or .childElementCount
(not recommended) since childNodes
gets allchildNodes, also Text-Nodes which are 4 in your case (the linebreaks).
您想要的是.children.length
或.childElementCount
(不推荐)因为childNodes
获取所有子节点,以及在您的情况下为 4 的文本节点(换行符)。
var temp = document.getElementById('element').parentNode;
child = temp.children;
console.log(child.length);
// or the following
console.log(temp.childElementCount);
回答by Elias Van Ootegem
childNodes
returns the 3 list items, their text content and the whitespace between them (not in all browsers, though). Three alternatives:
childNodes
返回 3 个列表项、它们的文本内容和它们之间的空格(但并非在所有浏览器中)。三种选择:
FF and Chrome:
elem.childElementCount
(will return 3)IE (&& FF AFAIK):
elem.childNodes.length
(===3)Old IE:
elem.children.length
FF 和 Chrome:(
elem.childElementCount
将返回 3)IE (&& FF AFAIK):
elem.childNodes.length
(===3)旧IE:
elem.children.length
回答by Julien Ch.
The childrenNodes property include all types of nodes: TEXT_NODE, ELEMENT_NODE, COMMEN_NODE, etc....
childrenNodes 属性包括所有类型的节点:TEXT_NODE、ELEMENT_NODE、COMMEN_NODE 等......
You need to count the number of elements, here is an example solutionbased on DOM that should work in all engines:
您需要计算元素的数量,这里是一个基于 DOM的示例解决方案,它应该适用于所有引擎:
var temp = document.getElementById('element').parentNode;
var children = temp.childNodes;
console.log(children.length); // 7
function countElements(children) {
var count=0;
for (var i=0, m=children.length; i<m; i++)
if (children[i].nodeType===document.ELEMENT_NODE)
count++;
return count;
}
console.info(countElements (children));? // 3
EDIT
编辑
Similarly if you want a function to retrieve all children Elements only using DOM, here is a function:
类似地,如果您希望一个函数仅使用 DOM 检索所有子元素,那么这里有一个函数:
function childElements(node) {
var elems = new Array();
var children = node.childNodes;
for (var i=0,i < children.length ; i++) {
if (children[i].nodeType===document.ELEMENT_NODE) {
elems.push(children[i]);
return elems;
}
}
}
console.info(childElements(temp).length);? //3