appendChild only works first time

2019-02-21 03:55发布

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 time. It does exactly what I want the first time, then fails to do anything on subsequent button presses. I had a bit of a poke around, and it seems that after the first append, the "newstuff.innerHTML" is emptied. After much fruitless searching, I decided to come and ask here.

The event handler is firing, the innerHTML of the variable is being appended, but I can't for the life of me work out why my variable is getting trashed.

The variables and data below have been changed to protect the innocent.

var button = document.getElementById('add_stuff');
var oldstuff = document.getElementById('element_id');
var newstuff = document.createElement('div');
newstuff.innerHTML = "<p>Super interesting content</p>";
button.onclick = function(event) {
    while (newstuff.firstChild) {
        oldstuff.appendChild(newstuff.firstChild);
    }
}

2条回答
冷血范
2楼-- · 2019-02-21 04:16

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.

查看更多
迷人小祖宗
3楼-- · 2019-02-21 04:17

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/

查看更多
登录 后发表回答