<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>
Run Code Online (Sandbox Code Playgroud)
我需要使用元素id获取子节点长度.我的代码返回7作为结果,但我只有3个节点.
Chr*_*oph 24
你想要的是.children.length或者.childElementCount(不推荐)因为childNodes得到所有的 childNodes,你的案例中的文本节点是4(换行符).
var temp = document.getElementById('element').parentNode;
child = temp.children;
console.log(child.length);
// or the following
console.log(temp.childElementCount);
Run Code Online (Sandbox Code Playgroud)
childNodes返回3个列表项,它们的文本内容和它们之间的空格(但不是在所有浏览器中).三种选择:
FF和Chrome :( elem.childElementCount将返回3)
IE(&& FF AFAIK):( elem.childNodes.length=== 3)
旧IE: elem.children.length
| 归档时间: |
|
| 查看次数: |
51199 次 |
| 最近记录: |