HTMLTableRowElement: insertCell() method
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.
The Note: You can not use The cell index of the new cell. If An Thrown if This example uses insertCell()
method of the HTMLTableRowElement
interface inserts a new
cell () into a table row ( ) and returns a
reference to the cell.
insertCell()
inserts the cell directly into the
row. The cell does not need to be appended separately
with Node.appendChild()
as would be the case if
Document.createElement()
had been used to create the new
element.
insertCell()
to create a new
element though.
Syntax
insertCell()
insertCell(index)
Parameters
index
Optionalindex
is -1
or equal to the number of cells, the cell is appended as the last cell in the row. If index
is omitted it defaults to -1
.Return value
HTMLTableCellElement
that references the new
cell.Exceptions
IndexSizeError
DOMException
index
is greater than the number of cells.Examples
HTMLTableRowElement.insertCell()
to append a new cell to a
row.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();
});
Result
Specifications
Specification HTML
# dom-tr-insertcell-devBrowser compatibility
See also
HTMLTableElement.insertRow()
HTMLTableCellElement