Skip to content Skip to sidebar Skip to footer

Appendchild In For Loop Only Adds 1 Child

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 of eac

Solution 1:

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

EDIT: If the element setup is really complicated and potentially includes children then you can also use Node.cloneNode

Solution 2:

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

Solution 3:

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

Post a Comment for "Appendchild In For Loop Only Adds 1 Child"