Search code examples
javascriptdom

Dynamic creation of table with DOM


Can someone tell me what's wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).

var tablearea = document.getElementById('tablearea');

var table = document.createElement('table');

var tr = [];

var td1 = document.createElement('td');
var td2 = document.createElement('td');

var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');

for (var i = 1; i < 4; i++){
    tr[i] = document.createElement('tr');   
    for (var j = 1; j < 4; j++){
        td1.appendChild(text1);
        td2.appendChild(text2);
        tr[i].appendChild(td1);
        tr[i].appendChild(td2);
    }           
    table.appendChild(tr[i]);

}

tablearea.appendChild(table);

Solution

  • You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

    var table = document.createElement('table');
    for (var i = 1; i < 4; i++) {
      var tr = document.createElement('tr');
    
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
    
      var text1 = document.createTextNode('Text1');
      var text2 = document.createTextNode('Text2');
    
      td1.appendChild(text1);
      td2.appendChild(text2);
      tr.appendChild(td1);
      tr.appendChild(td2);
    
      table.appendChild(tr);
    }
    document.body.appendChild(table);