2017-06-06 36 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是否僅適用於文本節點? –