克隆的元素未显示

Cloned element is not shown

以下代码应克隆给定元素并将其插入到之后:

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>

没有抛出异常,一切都在执行,但我看不到新元素。为什么?

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>