HTMLTableSectionElement: rows-Eigenschaft
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.
Die schreibgeschützte rows
-Eigenschaft des HTMLTableSectionElement
Interfaces gibt eine Live-[
HTMLCollection](/de/docs/Web/API/HTMLCollection)
zurück, die die Zeilen im Abschnitt enthält. Die HTMLCollection
ist live und wird automatisch aktualisiert, wenn Zeilen hinzugefügt oder entfernt werden.
Wert
Eine Live-[
HTMLCollection](/de/docs/Web/API/HTMLCollection)
von HTMLTableRowElement
-Objekten.
Beispiele
In diesem Beispiel erlauben zwei Schaltflächen das Hinzufügen und Entfernen von Zeilen aus dem Tabellenkörperabschnitt; außerdem wird ein <output>
-Element mit der aktuellen Anzahl der Zeilen in der Tabelle aktualisiert.
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();
});
Ergebnis
Spezifikationen
Specification |
---|
HTML # dom-tbody-rows |