HTMLTableElement: insertRow() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

HTMLTableElement 接口的 insertRow() 方法会在给定的 <table> 中插入一个新的行 (<tr>),并返回新行的引用。

如果一个表格有多个 <tbody> 元素,默认情况下,新行会被插入到最后一个 <tbody> 中。要将行插入到特定部分,请使用 HTMLTableSectionElement.insertRow()

注意: insertRow() 直接将行插入到表格中。无需像使用 Document.createElement() 创建新的 <tr> 元素那样单独追加该行。

语法

js
insertRow()
insertRow(index)

HTMLTableElement 是对 HTML <table> 元素的引用。

参数

index 可选

新行的行索引。如果 index-1 或等于行数,则该行将被追加为最后一行。如果省略 index,则默认为 -1

返回值

一个引用新行的 HTMLTableRowElement

异常

IndexSizeError DOMException

如果 index 大于行数,则抛出异常。

示例

此示例使用 insertRow(-1) 将新行追加到表格中。

然后,我们使用 HTMLTableRowElement.insertCell() 在新行中插入一个新单元格。(为了使 HTML 有效,<tr> 必须至少有一个 <td> 元素。)最后,我们使用 Document.createTextNode()Node.appendChild() 向单元格添加一些文本。

HTML

html
<table id="my-table">
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>Row 3</td>
  </tr>
</table>

JavaScript

js
function addRow(tableID) {
  // Get a reference to the table
  let tableRef = document.getElementById(tableID);

  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);

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

  // Append a text node to the cell
  let newText = document.createTextNode("New bottom row");
  newCell.appendChild(newText);
}

// Call addRow() with the table's ID
addRow("my-table");

结果

规范

规范
HTML
# dom-table-insertrow-dev

浏览器兼容性

另见