简体   繁体   中英

Appending tr to table appends a new tbody to html table using javascript

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)

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

Update:

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 specific tbody

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

Fiddle

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.

Updated Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM