HTMLTableRowElement: insertCell() method
The HTMLTableRowElement.insertCell() method inserts a new cell (<td>) into a table row (<tr>) and returns a reference to the cell.
Note: 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 <td> element.
You can not use insertCell() to create a new <th> element though.
Syntax
insertCell()
insertCell(index)
HTMLTableRowElement is a reference to an HTML <tr> element.
Parameters
-
index Optional
-
The cell index of the new cell. If index 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
An HTMLTableCellElement that references the new cell.
Exceptions
-
IndexSizeError DOMException
-
Thrown if index is greater than the number of cells.
Examples
This example uses HTMLTableElement.insertRow() to append a new row to a table.
We then use insertCell(0) to insert a new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild().
HTML
<table id="my-table">
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</table>
JavaScript
function addRow(tableID) {
let tableRef = document.getElementById(tableID);
let newRow = tableRef.insertRow(-1);
let newCell = newRow.insertCell(0);
let newText = document.createTextNode("New bottom row");
newCell.appendChild(newText);
}
addRow("my-table");
Result
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
insertCell |
1 |
12 |
1 |
5.5 |
≤12.1 |
3 |
4.4 |
18 |
4 |
≤12.1 |
1 |
1.0 |
index_parameter_negative_one |
1 |
12 |
20 |
5.5 |
≤15 |
3 |
4.4 |
18 |
20 |
≤14 |
1 |
1.0 |
index_parameter_optional |
1 |
12 |
20 |
5.5 |
15 |
3 |
4.4 |
18 |
20 |
14 |
1 |
1.0 |
See also