2017-04-08 46 views
0

我在入門級JavaScript課程,正在學習我們的文檔對象模型部分,我想了解下面的腳本沒有價值的原因,有人可以解釋它一點?爲什麼沒有顯示值(DOM)的原因

<!DOCTYPE html> 
 
<html> 
 

 
<body id="bdy"> 
 

 
    <h1 id="id00">Test 1</h1> 
 
    <h1 id="id01">Test2</h1> 
 
    <p id="id02"></p> 
 

 
    <script> 
 
    document.getElementById("id02").innerHTML = document.getElementById("bdy").childNodes[0].nodeValue; 
 
    </script> 
 

 
</body> 
 

 
</html>

+0

什麼不工作? –

+3

因爲孩子節點不是你想象的那樣。您需要跳過空文本節點 – mplungjan

+0

對於第一個元素,請使用'.firstElementChild'或'.children [0]' – 2017-04-08 16:25:19

回答

1

因爲childnode是不是你認爲它是。您需要跳過空textnodes,你可能要更這裏訪問節點

讀的textContenthttps://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace_in_the_DOM

在這裏:nodeValue vs innerHTML and textContent. How to choose?

for (var i = 0; i < document.getElementById("bdy").childNodes.length; i++) { 
 
    console.log(i, document.getElementById("bdy").childNodes[i].textContent) 
 
}
<body id="bdy"> 
 

 
    <h1 id="id00">Test 1</h1> 
 
    <h1 id="id01">Test2</h1> 
 
    <p id="id02"></p> 
 
</body>

這可能是你的意思是:

document.getElementById("id02").innerHTML = document.getElementById("bdy").children[0].textContent; 
 
<body id="bdy"> 
 

 
    <h1 id="id00">Test 1</h1> 
 
    <h1 id="id01">Test2</h1> 
 
    <p id="id02"></p> 
 
</body>