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

瀏覽器相容性

另見