HTMLTableSectionElement: свойство rows
Базовая поддержка Широко доступно
Эта функция хорошо зарекомендовала себя и работает на многих устройствах и версиях браузеров. Она доступна во всех браузерах с июля 2015 года.
Свойство rows только для чтения интерфейса HTMLTableSectionElement возвращает живой HTMLCollection, содержащий строки в разделе. HTMLCollection живое и автоматически обновляется при добавлении или удалении строк.
Значение
Живой HTMLCollection объектов HTMLTableRowElement.
Примеры
В этом примере две кнопки позволяют добавлять и удалять строки из раздела тела таблицы; также он обновляет элемент <output> количеством строк, в данный момент присутствующих в таблице.
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
// 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 |
Совместимость с браузерами
| Рабочий стол | Мобильные | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox для Android | Opera Android | Safari на iOS | Samsung Internet | WebView Android | |
rows |
1 | 12 | 1 | ≤12.1 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 | 4.4 |
См. также
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement/rows