2017-05-14 50 views
0

下面的代碼按預期工作。JS和HTML - cloneNode()不起作用

CloneNode.js

<!DOCTYPE html> 
<html> 
     <body> 
      <script src="../js/CloneNode.js"> 
      function myFunction(){ 
       var the_node = document.getElementById("myList").lastChild; 
       var the_clone = the_node.cloneNode(true); 
       document.getElementById("myList").appendChild(the_clone); 
       } 
      </script> 
      <ul id="myList"> 
      <li>Good morning</li> 
      <li>Hello</li></ul> 
      <p>Click on the button to CloneNode()</p> 
      <button onclick = "myFunction()">Copy it!</button> 
    </body> 
</html> 

它工作正常進行下面的代碼也:

<ul id="myList"><li>Good morning</li> 
<li>Hello</li></ul> 

OR

<ul id="myList"><li>Good morning</li><li>Hello</li></ul> 

但是,當我在上面的HTML </ul>之前輸入換行符代碼,如下所示,我沒有得到ou tput的。因此,在網頁上不添加<li>元素。

<ul id="myList"> 
<li>Good morning</li> 
<li>Hello</li> 
</ul> 

HTML代碼中的縮進如何影響輸出?還是有什麼我錯過了?

回答

1

Element.lastChild回報TextNode節點以及Element節點,新的行字符被解析爲一個空TextNode查詢時,這樣做,無論它的工作,改變

var the_node = document.getElementById("myList").lastChild;

var the_node = document.getElementById("myList").lastElementChild;

+0

謝謝@dummy。以上解決方案工作 – kanchan

+1

@ kanchan:您應該將其標記爲答案。 – Whothehellisthat