Thursday, 8 August 2013

What is the best way to create table in JS?

What is the best way to create table in JS?

I found two ways to create a table in JS:
First:
var table = document.getElementById ("table");
var row = table.insertRow (1);
var cell = row.insertCell (0);
cell.innerHTML = "New row";
Second:
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 2; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
The first as i see is specially created for the table, but the second is
mentioned on MDN, so i'm a bit confused what method to use?

No comments:

Post a Comment