HTMLTableRowElement: cells 属性
基线 广泛可用
此功能已经过良好验证,并且可以在许多设备和浏览器版本上运行。它自 2015 年 7 月.
报告反馈
值
HTMLTableRowElement
接口的只读属性 cells
返回一个包含行中单元格的实时 HTMLCollection
。HTMLCollection
是实时的,当添加或删除单元格时会自动更新。
示例
一个实时 HTMLCollection
,其中包含 HTMLTableCellElement
对象。
HTML
此示例使用
HTMLTableRowElement.cells
来显示一行中的单元格数量。<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
html
// 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();
});
js
规范
结果 |
---|
规范 # HTML 标准 |
浏览器兼容性
dom-tr-cells