如何在JavaScript的HTML表格主体中插入行

JérômeVerstrynge:

我有一个带有页眉和页脚的HTML表:

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

我正在尝试添加tbody以下内容:

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

但该行已添加到该tfoot部分中。

我该如何插入tbody

乔纳森·纳金(Jonathan Naguin):

如果您想在中添加行tbody,请获取对该行的引用并将其添加到其中。

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

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

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

工作演示在这里另外,您可以在insertRow 此处查看文档

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章