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

ぐ巨炮叔叔 提交于 2019-11-29 11:35:36

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);
    }
};

You're creating a single element and trying to re-add it multiple times. You need to create multiple elements.

When you run document.createElement that creates the element in the DOM. AppendChild is just setting the location. So you create one element and then move it to the same place many times. You want to instead create many elements and set their location once each

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

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

or alternatively (shorter but less flexible, only use this for a one-off)

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

    for(var i = 0; i < cards; i++){ 
        board.appendChild("<div class='card'></div>);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!