Reputation: 11205
Please check this fiddle: http://jsfiddle.net/tn4euhsn/8/
HTML:
<table id="tab" border=1>
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</table>
Javascript:
console.log("Here!");
var table = document.getElementById("tab");
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
var td1 = document.createElement("td");
td1.innerHTML= "r2col1";
var td2 = document.createElement("td");
td2.innerHTML= "r2col2";
trnew.appendChild(td1);
trnew.appendChild(td2);
table.appendChild(trnew);
console.log(table.outerHTML);
I am trying to append a new <tr>
to a table. But instead a <tbody><tr></tr></tbody>
gets appended, resulting in 2 <tbody>
elements in html table.
So whats wrong here? and how do I do it? (I don't want to use jquery)
Upvotes: 1
Views: 919
Reputation: 56509
Yes it already has a default tbody
tag so you have to use it instead of introducing new one.
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
Also you can simplify it like
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
for (var i=1; i<=2; i++) {
var td = document.createElement("td");
td.innerHTML = "r2col" + i;
trnew.appendChild(td);
}
table.appendChild(trnew);
console.log(table.outerHTML);
While trying to figure out the reason, I came across HTMLTableElement,
If a table has multiple tbody elements, by default, the new row is inserted into the last
tbody
. To insert the row into a specifictbody
Here is an updated version of the above code
var table = document.getElementById("tab");
var index = table.getElementsByTagName("tr").length;
var newRow = table.insertRow(index);
newRow.id = "row" + 2;
for (var i = 0; i < 2; i++) {
var newCell = newRow.insertCell(i);
var newText = document.createTextNode("r2col" + i);
newCell.appendChild(newText);
}
console.log(table);
Upvotes: 1
Reputation: 1510
It seems that the browser will give it a tbody by default, try this:
<table border=1>
<tbody id="tab">
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</tbody>
</table>
Append to the tbody not to the table.
Upvotes: 0