Tuesday, February 26, 2008

Creating dynamic HTML tables with Javascript

when creating a dynamic HTML table in javascript, first
1) create a TABLE
2) create a TBODY
3) create rows, TR
4) create cells, TD
5) append the cells TD to the rows TR
6) append the rows TR to the TBODY
if this is not done then the entire table will not be visible.
7) append the TBODY to the TABLE
8) attached the TABLE to the required DOM node in HTML document

complete code for the above steps:

var newTbody = document.createElement("tbody");
var mainTable = document.createElement("table");
var newTR = document.createElement("tr");
var newTD = document.createElement("td");
newTD.innerHTML = 'some text';
newTR.appendChild(newTD);
newTbody.appendChild(newTR);
mainTable.appendChild(newTbody);
document.getElementById('someDomID').appendChild(mainTable);


The following code without a TBODY ends up with the entire TABLE not being visible.

var mainTable = document.createElement("table");
var newTR = document.createElement("tr");
var newTD = document.createElement("td");
newTD.innerHTML = 'some text';
newTR.appendChild(newTD);
mainTable.appendChild(newTR);
document.getElementById('someDomID').appendChild(mainTable);

No comments: