How to insert row in HTML table body in Javascript

2019-01-04 00:14发布

I have an HTML table with a header and a footer:

<table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td> 
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>

I am trying to add a row in tbody with the following:

myTable.insertRow(myTable.rows.length - 1);

but the row is added in the tfoot section.

How to insert it tbody?

9条回答
Fickle 薄情
2楼-- · 2019-01-04 00:44

Basic Approach:

This should add html formatted content and show newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow   = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
查看更多
倾城 Initia
3楼-- · 2019-01-04 00:50

I have tried this,

this is working for me

var table=document.getElementById("myTable");
var row=table.insertRow(myTable.rows.length-2);
var cell1=row.insertCell(0);
查看更多
淡お忘
4楼-- · 2019-01-04 00:51

If you want to add a row into the tbody, get a reference to it and add it there.

var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row in the table at the last row
var newRow   = tableRef.insertRow(tableRef.rows.length);

// Insert a cell in the row at index 0
var newCell  = newRow.insertCell(0);

// Append a text node to the cell
var newText  = document.createTextNode('New row');
newCell.appendChild(newText);

A working demo here. Also you can check the documentation of insertRow here.

查看更多
登录 后发表回答