HTMLTableCellElement: cellIndex 属性

Baseline 已广泛支持

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

HTMLTableCellElement 接口的只读属性 cellIndex 表示一个单元格在其行(<tr>)中的位置。第一个单元格的索引是 0

返回单元格的索引,如果单元格不属于任何行,则返回 -1

示例

此示例为 tbody 中第一行的所有单元格编号添加了一个标签。

HTML

html
<table>
  <thead>
    <tr>
      <th>Item</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Bananas</td>
      <td>$2</td>
    </tr>
    <tr>
      <td>Rice</td>
      <td>$2.5</td>
    </tr>
  </tbody>
</table>

JavaScript

js
const rows = document.querySelectorAll("tbody tr");
const cells = rows[0].cells;

for (const cell of cells) {
  cell.textContent = `${cell.textContent} (cell #${cell.cellIndex})`;
}

结果

规范

规范
HTML
# dom-tdth-cellindex

浏览器兼容性