Body元素javascript上的子节点数

时间:2017-01-04 00:30:55

标签: javascript dom html-parsing document-body child-nodes

Body元素上的子节点数为1,即使没有任何内容。这只发生在Body元素中,但不适用于其他元素,例如div。在那种情况下,结果为0.为什么?          

<head>
<script>
  function run() {
    alert(document.body.childNodes.length);
  }
  window.addEventListener("load", run, false);
</script>
</head>

<body></body>

</html>

虽然结果是0

<!Doctype html>
<html>
<head>
<script>
  function run() {
    alert(document.body.getElementsByTagName("div")[0].childNodes.length);
  }
   window.addEventListener("load",run,false);
</script>
</head>
<body>
<div></div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

身体内部有空白。空格被视为“文本”,“文本”被视为节点。

如果稍微更改代码,则可以输出nodeName。在这种情况下,它输出#text

由于我们已经知道有1个节点,我们可以简单地输出childNodes[0]。如果你有多个,你可以循环它们并输出每个。

<head>
<script>
    function run() {
      alert(document.body.childNodes[0].nodeName);
    }
    window.addEventListener("load", run, false);
</script>
</head>

<body></body>

</html>

我无法摆脱body标记中的空格,但我可以使用div标记。

<!Doctype html>
<html>
<head>
<script>
  function run() {
        var length = document.body.getElementsByTagName("div")[0].childNodes.length;
        if(length > 0) {
            length += "\n" + document.body.getElementsByTagName("div")[0].childNodes[0].nodeName;
        }
    alert( length );
  }
   window.addEventListener("load",run,false);
</script>
</head>
<body>
<div></div>
</body>
</html>

如果在div标签(空格,换行符等)之间添加任何空格,则警报将包含文本节点。

编辑:它似乎与浏览器有关。这是IE,Firefox和Chrome中的行为。我不确定其他浏览器是否以这种方式运行。

答案 1 :(得分:0)

由于the HTML parsing algorithm的要求,在问题的代码段中,body最终包含两个换行符。所以它在DOM中有一个文本节点子节点。

使用该文档尝试document.documentElement.innerHTML,只需修改代码段,如:

<head>
<script>
  function run() {
    alert(document.body.childNodes.length);
    alert(document.documentElement.innerHTML);
  }
  window.addEventListener("load", run, false);
</script>
</head>

<body></body>

</html>

......你将得到的是:

<head>
<script>
  function run() {
    alert(document.body.childNodes.length);
    alert(document.documentElement.innerHTML);
  }
  window.addEventListener("load", run, false);
</script>
</head>

<body>


</body>

或者只是在浏览器devtools中查询问题中的文档或使用Live DOM Viewer