RainingChain RainingChain - 1 month ago 7
HTML Question

Convert a JS Array ìnto HTML Table | Weird <tbody> Tag?

When I use this code, all the information is displayed in only one column. Also, if I check with Google Chrome, there are many

<tbody>
tags that were added to table.innerHTML .

http://puu.sh/4oLmM.png

How can I make it so it displays the header and each
content[i]
horizontally?

<table id="table1" border=\"5\" cellpadding=\"10\">

<script>
var table = document.getElementById('table1');
table.innerHTML = '';

var header = ['Method','Gp/Exp','Exp/H']

var content = [
['Kill',1,100],
['Die',42,1222],
['Yo',1,1245]
]


//Header
table.innerHTML += '<tr>';
for(var i in header){
table.innerHTML += '<th>' + header[i] + '</th>';
}
table.innerHTML += '</tr>';

//Content
for(var i in content){
table.innerHTML += '<tr>';
for(var j in content[i]){
table.innerHTML += '<td>' + content[i][j] + '</td>';
}
table.innerHTML += '</tr>';
}
</script>

Answer

I suspect this is what Ian meant:

var html = '<tr>';

for(var i in header){
    html += '<th>' + header[i] + '</th>';
}

html += '</tr>';

for(var i in content){
    html += '<tr>';
    for(var j in content[i]){
        html += '<td>' + content[i][j] + '</td>';
    }
    html += '</tr>';
}

table.innerHTML = html;

The way you've done it, you're adding badly formed HTML to the element. The overall string is fine, but my guess is that every time you do table.innerHTML +=, it realises that you're creating a dodgy HTML string, and messes around with it to get something that is valid HTML.