2017-06-06 34 views
0

我运行这个Javascript代码,并获取body.childNode没有问题的nodeType和nodeName。但是,nodeValue无法显示。body.childNodes的nodeValue在哪里?

<!DOCTYPE html> 
<html> 
<body> 

<p>Click the button to get the node types of the body element's child nodes.</p> 
<button onclick="myFunction()">Try it</button> 
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is considered as nodes.</p> 
<!-- My personal comment goes here.. --> 
<div><strong>Note:</strong> Comments in the document are considered as comment nodes.</div> 
<p id="demo"></p> 

<script> 
function myFunction() { 
    var c = document.body.childNodes; 
    var txt = ""; 
    var i; 
    for (i = 0; i < c.length; i++) { 
     txt = txt + "notdType: "+ c[i].nodeType + " NodeName: "+c[i].nodeName+" NodeValue: "+c[i].nodeValue +"<br>"; 
    } 
    document.getElementById("demo").innerHTML = txt; 
} 
</script> 
</body> 
</html> 
+0

想一想:为什么代码遍历document.body.childNodes而不是找到它的nodeValue?难道是因为document.body没有nodeValue吗?然后尝试将没有nodeValue的主体与没有nodeValue的节点关联起来。然后,看看你是否可以找出为什么这些其他节点没有nodeValue。 – BoltClock

回答

0

元素节点没有节点值。相反,他们有自己的子节点。

+0

我尝试使用innerText来获取元素节点的值。这似乎是成功的。如果元素节点具有其子节点,我可以在元素节点之后添加firstChild并获取nodeValue吗? –

+0

文本节点和元素节点之间有什么区别? nodeValue是否仅适用于文本节点? –