I'm trying to generate a table with 3 rows and 3 cells e.g.
<table>
<tr>
   <td> 00 </td>    <td> 01 </td>    <td> 02 </td>
</tr>
<tr>
   <td> 10 </td>    <td> 11 </td>    <td> 12 </td>
</tr>
<tr>
   <td> 20 </td>    <td> 21 </td>    <td> 22 </td>
</tr>
</table>
The Javascript I'm using to do this is:
tab = document.getElementById('tab');
for(i=0; i<3; i++)
{ 
 tab.innerHTML += '<tr>';
  for(j=0; j<3; j++) 
  {
   tab.innerHTML += '<td id="'+i+''+j+'">'+i+''+j+'</td>'; 
  }
 tab.innerHTML += '</tr>';
}
The HTML being:
<table id="tab">
</table>
However, when I run the code all the table elements end up in the first column, so instead of a 3x3 table I get a 1x9 table.
Anyone know what I'm doing wrong?
You should use helper string variable for this task:
var tab = document.getElementById('tab'),
    str = '';
for (var i = 0; i < 3; i++) {
    str += '<tr>';
    for (var j = 0; j < 3; j++) {
        str += '<td id="' + i + '' + j + '">' + i + '' + j + '</td>';
    }
    str += '</tr>';
}
tab.innerHTML = str;
I would also recommend to make use of table API
var tab = document.getElementById('tab');
for (var i = 0; i < 3; i++) {
    var row = tab.insertRow(i);
    for (var j = 0; j < 3; j++) {
        var cell = row.insertCell(j);
        cell.id = i + '' + j;
        cell.innerHTML = i + '' + j;
    }
}
Basically why it happens. Whenever you set something like:
tab.innerHTML += '<tr>'
table content becomes not valid HTML so browser fixes it automatically making it look like something:
<tbody><tr></tr></tbody>
Further loops makes it even more confused hence a result.
Also take a look at cookie monster's answer, for it is more comprehensive to my mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With