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

瀏覽器相容性

另見