2017-04-01 124 views
1

下面的代碼應該克隆給定元素後插入:克隆的元素不被顯示

function cloneMore(element) { 
    var newElement = element.cloneNode(true); 
    element.parentNode.insertBefore(newElement, element.nextSibling); 
} 
var addChoice = document.getElementById("add-choice") 
addChoice.onclick = (function(){cloneMore(document.getElementById("choices").lastChild);}) 

的HTML如下:

<ul id="choices"> 
    <!-- form elements --> 
</ul> 
<p><a id="add-choice">Add another choice</a></p> 

沒有拋出異常,一切都執行了,但我看不到新元素。爲什麼?

+0

控制檯登錄它,看看它是否是克隆連 –

回答

2

lastChild選擇所有節點類型,而不僅僅是元素。所以你可能會克隆一個TextNode \n

我想你想要的是lastElementChild

function cloneMore(element) { 
 
    var newElement = element.cloneNode(true); 
 
    element.parentNode.insertBefore(newElement, element.nextSibling); 
 
} 
 
var addChoice = document.getElementById("add-choice") 
 
addChoice.onclick = function() { 
 
    var choices = document.getElementById("choices"); 
 
    cloneMore(choices.lastElementChild); // only Elements 
 
    console.log('lastChild type : ', choices.lastChild.nodeName); 
 
}
<ul id="choices"> 
 
    <li> choice </li> 
 
</ul> 
 
<p><a href="#" id="add-choice">Add another choice</a></p>