Programming in javascript: appendChild in for loop only adds 1 child on newest questions tagged javascript – Stack Overflow

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 each grid square must be calculated and divided by the number of pixels available to get an exact size grid.

I’ve done all this, but I have a problem adding in the necessary table elements to create the grid. My code is in full working order, except when I use the appendChild() function inside a for loop it only ever appends a single child, when it should be appending up to a couple of hundred.

My code:

grid.show = function(event)
{
    var e = event;

    if(grid.show_grid == false)
    {
        grid.show_grid = true;

        parent.document.getElementById("grid_table").style.display = "block";

        // Get grid (table) and create some elements.
        grid.get_grid = parent.document.getElementById("grid_table");
        grid.tr       = parent.document.createElement("tr");
        grid.td       = parent.document.createElement("td");

        // Clear the grid of all squares so we don't have to worry about subtracting anything.
        grid.get_grid.innerHTML = "";

        // Calculate the number of horizontal and vertical squares.
        var horizontal = Math.ceil(grid.total_width / grid.size);
        var vertical   = Math.ceil(grid.total_height / grid.size);

        // This was a nested loop, removed for demonstration.
        // Attempting to add 10 "<tr><td></td></tr>" to the table.
        for(var j = 0; j < 10; j++)
        {
            grid.tr.appendChild(grid.td);
        }

        //console.log(grid.tr);

        // Add the elements to the table.
        grid.get_grid.appendChild(grid.tr);

    }
    else
    {   
        grid.show_grid = false;
        parent.document.getElementById("grid_table").style.display = "none";
    }
}

This only ever returns a single table row with single table data inside, like so:

<tr>
    <td></td>
</tr>

I’ve already looked at this page and this page, and they sound promising but I just can’t figure out how to make this work.

See Answers


source: http://stackoverflow.com/questions/12730824/appendchild-in-for-loop-only-adds-1-child
Programming in javascript: programming-in-javascript

Leave a Reply