`appendChild` inside a `for` loop just replaces item created by `createElement`

Cammy picture Cammy · Mar 26, 2013 · Viewed 14.6k times · Source

I Googled a lot about creating multiple items with appendChild, but I’m not understanding how it works. My appendChild just replaces instead of adding many.

var startGame;
var cards = 16;
var newDeck = [];

startGame = function(){
    var startBtn = document.getElementById('start');
    var board = document.getElementById('game-board');
    var backside = document.createElement("div");
    backside.className = 'card';

    startBtn.onclick = function(){
        removeButton = document.getElementById("start");
        removeButton.parentNode.removeChild(removeButton);

        for(var i = 0; i < cards; i++){ 
            board.appendChild(backside);
        }
    };
};

I also read you can do this with innerHTML, but that leaves me confused as well. Does anyone have a more detailed explanation on how to make this work?

Answer

Denys S&#233;guret picture Denys Séguret · Mar 26, 2013

From the MDN on appendChild :

Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

When you append an element that is yet in the DOM, you move it from its old place. Create the element in the loop :

startBtn.onclick = function(){
    removeButton = document.getElementById("start");
    removeButton.parentNode.removeChild(removeButton);

    for(var i = 0; i < cards; i++){ 
        var backside = document.createElement("div");
        backside.className = 'card';
        board.appendChild(backside);
    }
};