Search code examples
javascripthtml-tableappendchildcreateelement

Dynamically creating a table in Javascript


I have got a working table that when the button is pushed, a table is dynamically created by looping through an array and displaying that data in each cell.

However the problem arises when I am trying to add a table header for my table, and I'm not sure what I am doing wrong.

Here is my current working code: (although doesn't seem to work in JSFiddle?!)

And here is the code I am trying to add: (which must be wrong)

var thd=document.createElement("thead");
tab.appendChild(thd);

var tr= document.createElement("tr"); 
tbdy.appendChild(tr); 

var th= document.createElement("th");
th.appendChild(document.createTextNode("Name");
tr.appendChild(th);

Any help would be greatly appreciated,


Solution

  • You can use a loop to avoid duplicating code. For example:

    var columns = ["Name", "Age", "Degree"];
    
    var thd = document.createElement("thead");
    tab.appendChild(thd);
    
    var tr = document.createElement("tr"); 
    thd.appendChild(tr);
    
    for (var i = 0; i < columns.length; i++) {
        var th = document.createElement("th");
        th.appendChild(document.createTextNode(columns[i]));
        tr.appendChild(th);    
    }
    

    Demo: http://jsfiddle.net/ahEkH/6/