appendChild only works first time

前端 未结 2 898
醉酒成梦
醉酒成梦 2021-01-16 06:30

I want to repeatedly append the same stuff to an element via a button and event handler on the same page.

The problem I\'m encountering is that it only works first t

相关标签:
2条回答
  • 2021-01-16 07:00

    I think appendChild will actually move firstChild, not clone it. To clone it, you can use the cloneNode method on firstChild first, or get the HTML for firstChild and then use innerHTML again to append it.

    0 讨论(0)
  • 2021-01-16 07:05

    This is because a DOM node can only exist in one place in the DOM. When you call lineitems.appendChild(newstuff.firstChild), it is removing it from the original place and adding it to the new location. This means it will only work once.

    That being said, this would repeatedly add the markup like you want:

    button.onclick = function(event) {
        lineitems.innerHTML += newstuff.innerHTML;
    };
    

    See http://jsfiddle.net/LAKkQ/

    0 讨论(0)
提交回复
热议问题