HTMLTableSectionElement: insertRow() 方法

Baseline 已广泛支持

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

insertRow() 方法属于 HTMLTableSectionElement 接口,用于在给定的表格节元素(<thead><tfoot><tbody>)中插入一个新行(<tr>),然后返回该新行的引用。

注意: insertRow() 会直接将行插入到节中。与使用 Document.createElement() 创建新的 <tr> 元素后需要单独追加不同,这里不需要单独追加。

语法

js
insertRow()
insertRow(index)

参数

index 可选

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

返回值

一个 HTMLTableRowElement,它引用新创建的行。

异常

IndexSizeError DOMException

如果 index 大于行的数量,或者小于 -1,则抛出此异常。

示例

在此示例中,两个按钮允许您在表格正文节中添加和删除行;它还会使用表格中当前行的数量来更新一个 <output> 元素。

HTML

html
<table>
  <thead>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
  </thead>
  <tbody>
    <tr>
      <td>X</td>
      <td>Y</td>
      <td>Z</td>
    </tr>
  </tbody>
</table>
<button id="add">Add a row</button>
<button id="remove">Remove last row</button>
<div>This table's body has <output>1</output> row(s).</div>

JavaScript

js
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // The collection is live, therefore always up-to-date
const rowNumberDisplay = document.querySelectorAll("output")[0];

const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");

function updateRowNumber() {
  rowNumberDisplay.textContent = rows.length;
}

addButton.addEventListener("click", () => {
  // Add a new row at the end of the body
  const newRow = bodySection.insertRow();

  // Add cells inside the new row
  ["A", "B", "C"].forEach(
    (elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
  );

  // Update the row counter
  updateRowNumber();
});

removeButton.addEventListener("click", () => {
  // Delete the row from the body
  bodySection.deleteRow(-1);

  // Update the row counter
  updateRowNumber();
});

结果

规范

规范
HTML
# dom-tbody-insertrow

浏览器兼容性

另见