HTML : draw table using innerHTML

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

I want to draw a table using Javascript. So I wrote the code like above. I think it draw one row that has 10 columns, but it doesn't work. Anyone know about this problem???



I think the main problem is that your attributes are not quoted.

But it's almost always a bad idea to repeatedly update the content of a dom element in a loop—each time you update dom content it causes some internal work to be done by the browser to make sure the page layout is current.

I would build the html string up locally, then make one final update when done. (and of course make sure your attributes are quoted)

document.getElementById("outputDiv").innerHTML = "";

var newTable = "<table border='1' width='100%'><tr>";
for(j = 1; j <= 10; j++) { //opening braces should always be on the same line in JS
    newTable += "<td align='center'>" + String.fromCharCode(j+64) + "</td>";
newTable += "</tr></table>";

document.getElementById("outputDiv").innerHTML = newTable;

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>";
    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');
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);


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


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

Use jQuery.

for(j=1; j<=10; j++)



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.