HTMLTableSectionElement:rows 属性
rows
是 HTMLTableSectionElement
接口的只读属性,它返回一个包含该部分中所有行的实时 HTMLCollection
。HTMLCollection
是实时的,并且在添加或删除行时会自动更新。
值
示例
在此示例中,两个按钮允许您向表格主体部分添加和删除行;它还会使用表格中当前的行数更新 <output>
元素。
HTML
html
<table>
<thead>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</thead>
<tbody>
<tr>
<td>X</td>
<td>Y</td>
<td>Z</td>
</tr>
</tbody>
</table>
<button id="add">Add a row</button>
<button id="remove">Remove last row</button>
<div>This table's body has <output>1</output> row(s).</div>
JavaScript
js
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // The collection is live, therefore always up-to-date
const rowNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateRowNumber() {
rowNumberDisplay.textContent = rows.length;
}
addButton.addEventListener("click", () => {
// Add a new row at the end of the body
const newRow = bodySection.insertRow();
// Add cells inside the new row
["A", "B", "C"].forEach(
(elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
);
// Update the row counter
updateRowNumber();
});
removeButton.addEventListener("click", () => {
// Delete the row from the body
bodySection.deleteRow(-1);
// Update the row counter
updateRowNumber();
});
结果
规范
规范 |
---|
HTML 标准 # dom-tbody-rows |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。