HTMLTableSectionElement:rows 属性

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

HTMLTableSectionElement 接口的 rows 只读属性返回一个包含当前分段中行属性的动态 HTMLCollection。此 HTMLCollection 是动态的,并在添加或移除行时自动更新。

一个动态 HTMLTableRowElementHTMLCollection 对象。

示例

在这个示例中,有两个按钮允许你对表格主体添加和移除行,它还使用表中当前行数更新 <output> 元素。

HTML

html
<table>
  <thead>
    <th>列 1</th>
    <th>列 2</th>
    <th>列 3</th>
  </thead>
  <tbody>
    <tr>
      <td>X</td>
      <td>Y</td>
      <td>Z</td>
    </tr>
  </tbody>
</table>
<button id="add">添加一行</button>
<button id="remove">移除最后一行</button>
<div>表格主体有 <output>1</output> 行。</div>

JavaScript

js
// 获取相关接口元素
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // 集合是动态的,因此其总是最新的
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", () => {
  // 在主体的末尾添加一个新行
  const newRow = bodySection.insertRow();

  // 在新行内添加单元格
  ["A", "B", "C"].forEach(
    (elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
  );

  // 更新行计数
  updateRowNumber();
});

removeButton.addEventListener("click", () => {
  // 从主体删除行
  bodySection.deleteRow(-1);

  // 更新行计数
  updateRowNumber();
});

结果

规范

Specification
HTML
# dom-tbody-rows

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
rows

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见