appendChild in for loop only adds 1 child

后端 未结 3 410
轻奢々
轻奢々 2021-01-05 10:38

In JavaScript I am creating a grid (the type of grid you see in Photoshop) with HTML tables. The grid size is going to be variable, i.e., changeable by the user, so the size

相关标签:
3条回答
  • 2021-01-05 11:09

    If you want to make one copy of the element, you will need to clone it. Use cloneNode()

    So change

    grid.tr.appendChild(grid.td);
    

    to

    grid.tr.appendChild(grid.td.cloneNode(true));
    
    0 讨论(0)
  • 2021-01-05 11:25
    for(var j = 0; j < 10; j++)
    {
            grid.tr.appendChild(grid.td);
    }
    

    should be

    for(var j = 0; j < 10; j++) {
        var newTd = parent.document.createElement('td');
        grid.tds.push(newTd); // if you need it, not sure why though
        grid.tr.appendChild(newTd);
    }
    
    0 讨论(0)
  • 2021-01-05 11:28

    You are appending the same element over and over. You need to call document.createElement each time you wish to have a new element.

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