HTMLTableRowElement: insertCell() Methode
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 Note: Sie können Der Zellindex der neuen Zelle. Wenn Ein Wird ausgelöst, wenn Dieses Beispiel verwendet insertCell()
Methode der HTMLTableRowElement
Schnittstelle fügt eine neue Zelle () in eine Tabellenzeile ( ) ein und gibt eine Referenz auf die Zelle zurück.
insertCell()
fügt die Zelle direkt in die
Zeile ein. Die Zelle muss nicht separat mit Node.appendChild()
angehängt werden, wie es der Fall wäre, wenn Document.createElement()
verwendet worden wäre, um das neue Element zu erstellen.
insertCell()
jedoch nicht verwenden, um ein neues
Element zu erstellen.
Syntax
insertCell()
insertCell(index)
Parameter
index
Optionalindex
-1
oder gleich der Anzahl der Zellen ist, wird die Zelle als letzte Zelle in der Zeile angehängt. Wenn index
weggelassen wird, ist der Standardwert -1
.Rückgabewert
HTMLTableCellElement
, das auf die neue Zelle verweist.Ausnahmen
IndexSizeError
DOMException
index
größer als die Anzahl der Zellen ist.Beispiele
HTMLTableRowElement.insertCell()
, um eine neue Zelle an eine Zeile anzuhängen.HTML
C1
C2
C3
C4
C5
Cell 1
Cell 2
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
Specification HTML
# dom-tr-insertcell-devBrowser-Kompatibilität
Siehe auch
HTMLTableElement.insertRow()
HTMLTableCellElement