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

瀏覽器相容性