TableRow insertCell() Method

Definition and Usage

insertCell() The method inserts the cell into the current row.

Tip:Please use deleteCell() Method Delete the cell in the current table row.

See also:

HTML Reference Manual:HTML <tr> Tag

Example

Example 1

Insert a new cell containing content at the beginning of the table row with id="myRow":

var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";

Try It Yourself

More examples are provided at the bottom of the page.

Grammar

tablerowObject.insertCell()index)
Parameter Description
index

It is required in Firefox and Opera, and optional in IE, Chrome, and Safari.

Number (starting from 0), specifies the position of the new cell in the current row.

Value 0 will cause the new cell to be inserted at the first position. You can also use the value -1, which will cause the new cell to be inserted at the last position.

If this parameter is omitted, insertCell() will insert a new cell at the last position in IE, and at the first position in Chrome and Safari.

Technical details

Return value:

The inserted cell element.

Browser support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support

More examples

Example 2

Insert a new cell containing content at the end of the table row with id="myRow":

var row = document.getElementById("myRow");
var x = row.insertCell(-1);
x.innerHTML = "New cell";

Try It Yourself

Example 3

Insert a new cell containing content at index 2 in the table row with id="myRow":

var row = document.getElementById("myRow");
var x = row.insertCell(2);
x.innerHTML = "New cell";

Try It Yourself

Example 4

Insert a new cell at the beginning of the first table row. The rows collection (.rows[0]) returns a collection of all <tr> elements in the table with id "myTable".

The number [0] specifies the element to be retrieved, in this case, the first table row. Then we use insertCell() to insert a new cell at the index position -1:

var firstRow = document.getElementById("myTable").rows[0];
var x = firstRow.insertCell(-1);
x.innerHTML = "New cell";

Try It Yourself

Example 5

Delete the first cell from the table row with id="myRow":

var row = document.getElementById("myRow");
row.deleteCell(0);

Try It Yourself

Example 6

Insert a new row at the beginning of the table.

The insertRow() method inserts a new row at a specified index in the table, in this example, at the first position (beginning) of the table with id="myTable".

Then we use the insertCell() method to add a cell to the new row.

var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

Try It Yourself