Javascript - 子节点数 [英] Javascript - child node count
本文介绍了Javascript - 子节点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<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>
我需要使用元素ID获取子节点长度。结果我的代码返回7,但是我只有3个节点。
I need to get the child node length using element id. My code returns 7 as a result but I have only 3 nodes.
推荐答案
你想要的是 .children.length
或 .childElementCount
(不推荐),因为 childNodes
获取所有子节点,还有4个文本节点你的案例(换行)。
What you want is .children.length
or .childElementCount
(not recommended) since childNodes
gets all childNodes, also Text-Nodes which are 4 in your case (the linebreaks).
var temp = document.getElementById('element').parentNode;
child = temp.children;
console.log(child.length);
// or the following
console.log(temp.childElementCount);
这篇关于Javascript - 子节点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文