Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么一个空的body标记中有两个ghost节点?_Javascript_Html_Dom - Fatal编程技术网

Javascript 为什么一个空的body标记中有两个ghost节点?

Javascript 为什么一个空的body标记中有两个ghost节点?,javascript,html,dom,Javascript,Html,Dom,我编写了一个计算DOM中节点总数的函数 var nodeCount = 1; //1 for the first node, assuming it IS a node function traverseDom(currentNode) { if(nodeCount == 1 || !(currentNode.nextSibling)){ if(currentNode.firstChild){ nodeCount += 1; //console.log(currentNod

我编写了一个计算DOM中节点总数的函数

var nodeCount = 1; 
//1 for the first node, assuming it IS a node
function traverseDom(currentNode) {
  if(nodeCount == 1 || !(currentNode.nextSibling)){
    if(currentNode.firstChild){
    nodeCount += 1;
//console.log(currentNode.firstChild.nodeType);
    traverseDom(currentNode.firstChild);
    }
  }else{
     if(currentNode.nextSibling){
      nodeCount += 1;
      traverseDom(currentNode.nextSibling);
     }
  }
return nodeCount;
}
console.log(traverseDom(document.getElementsByTagName("body")[0]));
该函数将根节点作为参数,从该点遍历DOM并返回节点数。它适用于其他节点,但当我传递
body
元素时,即使标记之间没有空格,函数始终返回3。这两个不可见节点来自哪里? 以下是HTML结构:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body></body>
</html>

JS-Bin

提示:您也可以
console.log()
节点。浏览器控制台不限于字符串。文本节点!行尾和空格可以算作节点。@evolutionxbox,但没有行尾或空格。它只是
而不是
。例如,如果我在其中放置一个
,并将
document.getElementsByTagName(“div”)[0]
作为参数传递,它将返回2。元素节点(div)和文本节点(空格)。为什么执行
console.log(document.getElementsByTagName(“body”)[0].firstChild.nodeType)时,
body的结果会不同它将1记录到控制台。这意味着,
节点不仅有第一个子节点,而且它的类型是1(元素),而不是3(文本)(请参阅更多:)JSBin会自动在主体中插入脚本元素,以便实时重新加载。这可能是您看到的“ghost”元素的原因。提示:您也可以
console.log()
节点。浏览器控制台不限于字符串。文本节点!行尾和空格可以算作节点。@evolutionxbox,但没有行尾或空格。它只是
而不是
。例如,如果我在其中放置一个
,并将
document.getElementsByTagName(“div”)[0]
作为参数传递,它将返回2。元素节点(div)和文本节点(空格)。为什么执行
console.log(document.getElementsByTagName(“body”)[0].firstChild.nodeType)时,
body的结果会不同它将1记录到控制台。这意味着,
节点不仅有第一个子节点,而且它的类型是1(元素),而不是3(文本)(请参阅更多:)JSBin会自动在主体中插入脚本元素,以便实时重新加载。这可能是你看到的“幽灵”元素的原因。