Search code examples
javascripthtmldomappendchild

rowIndex when creating a table with Javascript


I have the following function to append rows and cells to an empty table:

        function createTable(size) {
            var table = document.getElementById("gameTable");
            for (var i=0; i<size; i++) {
                var tr = document.createElement("tr");
                for (var j=0; j<size; j++) {
                    var td = document.createElement("td");
                    tr.appendChild(td);
                }
                table.appendChild(tr);
                tr.rowIndex = i;
            }

        }

So far so good.

My problem is that later, when I tried to reach specific cells inside the table:

var x = target.parentNode.rowIndex;
var y = target.cellIndex; 

table.rows[x].cells[y].innerHTML = 'blah'

target is the specific TD that was clicked.

the rows[x] index is always -1. Every time I try the line above I get an error: "cannot read property 'cells' of undefined"
I even tried manually setting the rowIndex of each Row to what it should be (inside the function), but to no avail.

The cellIndex comes out fine, but the rowIndex is -1 and each and every one of the newly created table rows.

What can I do to correct this?


Solution

  • This can be solved by appending the <tr> elements into a <tbody>.

            function createTable(size) {
                var table = document.getElementById("gameTable");
                var tb = document.createElement("tbody");
                for (var i=0; i<size; i++) {
                    var tr = document.createElement("tr");
                    for (var j=0; j<size; j++) {
                        var td = document.createElement("td");
                        tr.appendChild(td);
                    }
                    tb.appendChild(tr);
                }
                table.appendChild(tb);
            }