2017-06-06 1 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

考えてみましょう:なぜコードはnodeValueを見つけるのではなく、document.body.childNodesを反復していますか? document.bodyにもnodeValueがないためでしょうか?次に、nodeValueを持たないノードとnodeValueを持たないボディを関連付けるようにしてください。そして、他のノードがnodeValuesを持たない理由を理解できるかどうかを確認してください。 – BoltClock

答えて

0

要素ノードにはノード値がありません。代わりに、彼ら自身の子ノードがあります。

+0

要素ノードの値を取得するためにinnerTextを使用しようとしています。それは成功したようです。 Elementノードに子ノードがある場合、Elementsノードの後に​​firstChildを追加してnodeValueを取得できますか? –

+0

テキストノードと要素ノードの違いは何ですか? nodeValueはテキストノードにのみ適用されますか? –

関連する問題