Baseline Widely available
Die insertCell()
-Methode des HTMLTableRowElement
-Interfaces fügt eine neue Zelle (<td>
) in eine Tabellenzeile (<tr>
) ein und gibt eine Referenz auf die Zelle zurück.
Hinweis:>insertCell()
fügt die Zelle direkt in die Zeile ein. Die Zelle muss nicht separat mit Node.appendChild()
hinzugefügt werden, wie es der Fall wäre, wenn Document.createElement()
verwendet worden wäre, um das neue <td>
-Element zu erstellen.
Sie können insertCell()
jedoch nicht verwenden, um ein neues <th>
-Element zu erstellen.
insertCell()
insertCell(index)
Parameter
index
Optional
Der Zellindex der neuen Zelle. Wenn index
-1
ist oder der Anzahl der Zellen entspricht, wird die Zelle als letzte Zelle in der Zeile hinzugefügt. Wenn index
weggelassen wird, ist der Standardwert -1
.
Ein HTMLTableCellElement
, das auf die neue Zelle verweist.
IndexSizeError
DOMException
Wird ausgelöst, wenn index
gröÃer als die Anzahl der Zellen ist.
Dieses Beispiel verwendet HTMLTableRowElement.insertCell()
, um eine neue Zelle an eine Zeile anzuhängen.
<table>
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>C3</th>
<th>C4</th>
<th>C5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</tbody>
</table>
<button id="add">Add a cell</button>
<button id="remove">Remove last cell</button>
<div>This first row has <output>2</output> cell(s).</div>
table {
border-collapse: collapse;
}
th,
td,
table {
border: 1px solid black;
}
button {
margin: 1em 1em 1em 0;
}
JavaScript
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // Select the first row of the body section
const cells = row.cells; // The collection is live, therefore always up-to-date
const cellNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateCellNumber() {
cellNumberDisplay.textContent = cells.length;
}
addButton.addEventListener("click", () => {
// Add a new cell at the end of the first row
const newCell = row.insertCell();
newCell.textContent = `Cell ${cells.length}`;
// Update the row counter
updateCellNumber();
});
removeButton.addEventListener("click", () => {
// Delete the row from the body
row.deleteCell(-1);
// Update the row counter
updateCellNumber();
});
Ergebnis Spezifikationen Browser-Kompatibilität Siehe auch MDN-Feedback-Box War diese Ãbersetzung hilfreich?
Diese Seite wurde automatisch aus dem Englischen übersetzt.
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