我正在尝试计算主体中的元素数量,并且我正在这样做
<html>
<head>
<title>Practice Javascript</title>
<script>
window.onload = count;
function count()
{
var ele = document.body.childNodes;
alert(ele.length);
}
</script>
</head>
<body>
<p>Text one</p>
<p>Text Two</p>
</body>
</html>
我期望输出为 2,但结果是 5
但是当我通过以下代码删除新行
<html>
<head>
<title>Practice Javascript</title>
<script>
window.onload = count;
function count()
{
var ele = document.body.childNodes;
alert(ele.length);
}
</script>
</head>
<body><p>Text one</p><p>Text Two</p>
</body>
</html>
它给出输出 3 Dom树如何评估不存在的子节点?
最佳答案
childNodes
包含文本节点。请改用 childElementCount
。
另一方面,children
不包含文本节点。所以你可以使用node.children.length
。
在您的例子中,该 html 中有 3 个新行,因此 3+2 是 5。
关于javascript - 新行增加了我的 body.childNodes 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18850507/