Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML : draw table using innerHTML

document.getElementById("outputDiv").innerHTML = "";
document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>";
for(j=1;j<=10;j++)
{
    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???

like image 454
Jimmy Avatar asked Dec 08 '12 07:12

Jimmy


People also ask

Can you put HTML in innerHTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .


1 Answers

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

like image 181
TwiNight Avatar answered Oct 10 '22 11:10

TwiNight