HTMLTableRowElement: insertCell() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLTableRowElement 介面的 insertCell() 方法用於在表格行(<tr>)中插入一個新的單元格(<td>),並返回對該單元格的引用。

注意: insertCell() 會直接將單元格插入到行中。該單元格不需要像使用 Document.createElement() 建立新的 <td> 元素時那樣,單獨使用 Node.appendChild() 來追加。

不過,你不能使用 insertCell() 來建立新的 <th> 元素。

語法

js
insertCell()
insertCell(index)

引數

index 可選

新單元格的索引。如果 index-1 或等於單元格的數量,則單元格將作為行的最後一個單元格被追加。如果省略 index,則預設為 -1

返回值

一個 HTMLTableCellElement,引用新單元格。

異常

IndexSizeError DOMException

如果 index 大於單元格的數量,則會丟擲此異常。

示例

此示例使用 HTMLTableRowElement.insertCell() 將一個新單元格追加到行中。

HTML

html
<table>
  <thead>
    <tr>
      <th>C1</th>
      <th>C2</th>
      <th>C3</th>
      <th>C4</th>
      <th>C5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </tr>
  </tbody>
</table>

<button id="add">Add a cell</button>
<button id="remove">Remove last cell</button>
<div>This first row has <output>2</output> cell(s).</div>

JavaScript

js
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // Select the first row of the body section
const cells = row.cells; // The collection is live, therefore always up-to-date
const cellNumberDisplay = document.querySelectorAll("output")[0];

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

function updateCellNumber() {
  cellNumberDisplay.textContent = cells.length;
}

addButton.addEventListener("click", () => {
  // Add a new cell at the end of the first row
  const newCell = row.insertCell();
  newCell.textContent = `Cell ${cells.length}`;

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

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

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

結果

規範

規範
HTML
# dom-tr-insertcell-dev

瀏覽器相容性

另見