Baseline Widely available
Die insertRow()
-Methode des HTMLTableSectionElement
-Interfaces fügt eine neue Zeile (<tr>
) in das angegebene Tabellenabschnittselement (<thead>
, <tfoot>
oder <tbody>
) ein und gibt dann eine Referenz auf diese neue Zeile zurück.
Hinweis:>insertRow()
fügt die Zeile direkt in den Abschnitt ein. Die Zeile muss nicht separat angehängt werden, wie es der Fall wäre, wenn Document.createElement()
verwendet worden wäre, um das neue <tr>
-Element zu erstellen.
insertRow()
insertRow(index)
Parameter
index
Optional
Der Zeilenindex der neuen Zeile. Wenn index
-1
oder gleich der Anzahl der Zeilen ist, wird die Zeile als letzte Zeile angehängt. Wenn index
weggelassen wird, ist der Standardwert -1
.
Ein HTMLTableRowElement
, das auf die neue Zeile verweist.
IndexSizeError
DOMException
Wird ausgelöst, wenn index
gröÃer als die Anzahl der Zeilen oder kleiner als -1
ist.
In diesem Beispiel ermöglichen zwei Schaltflächen das Hinzufügen und Entfernen von Zeilen im Tabellenkörper; auÃerdem wird ein <output>
-Element mit der Anzahl der aktuell in der Tabelle vorhandenen Zeilen aktualisiert.
<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>
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid black;
}
button {
margin: 1em 1em 1em 0;
}
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 Browser-Kompatibilität Siehe auch
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4