HTMLTableRowElement: deleteCell() 方法

Baseline 已广泛支持

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

HTMLTableRowElement 接口的 deleteCell() 方法会从给定的 <tr> 中移除指定的行单元格。

语法

js
deleteCell(index)

参数

index

要移除的单元格的索引。如果 index-1 或等于单元格数量,则会移除行的最后一个单元格。

返回值

无(undefined)。

异常

IndexSizeError DOMException

如果 index 大于单元格数量,或者小于 -1,则会抛出错误。

示例

此示例使用 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-deletecell

浏览器兼容性

另见