HTML : draw table using innerHTML

I ran into this problem years ago, too.

The problem is that when you use the innerHTML property to add HTML, after each update, the underlying engine will close unclosed tag (and fix other bad HTML) for you. So after the second line, the <table> and <tr> tags are automatically closed and all content after that will just be written outside the table.


Method 1
(The easy way)

Use a string to store the HTML for the whole table and update it all at once.

var HTML = "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
    HTML += "<td align=center>"+String.fromCharCode(j+64)+"</td>";
}
HTML += "</tr></table>";
document.getElementById("outputDiv").innerHTML = HTML;


Fiddle


Method 2
(The better way)

Use DOM functions

var table = document.createElement('table');
table.setAttribute('border','1');
table.setAttribute('width','100%')
var row = table.insertRow(0);
for(j=1; j<=10; j++){
    var text = document.createTextNode(String.fromCharCode(j+64));
    var cell = row.insertCell(j-1);
    cell.setAttribute('align','center')
    cell.appendChild(text);
}
document.getElementById("outputDiv").appendChild(table);

Fiddle


Method 2 enhanced
(The yet better way)

Use CSS instead of HTML attributes. The latter is generally depreciated as of latest specs.

A great resource to start learning CSS is the Mozilla Developer Network

Fiddle


Method 3
(The long way, but the best in the long-run)

Use jQuery.

$('<table>').append('<tr>').appendTo('#outputDiv');
for(j=1; j<=10; j++)
    $('<td>').text(String.fromCharCode(j+64)).appendTo('tr');

Fiddle

Leave a Comment