Table insertRow() method

Definition and Usage

insertRow() The method creates an empty <tr> element and add it to the table.

insertRow() The method inserts a new row at the specified index in the table.

Note:The <tr> element must contain <th> or <td> elements.

Tip:Use deleteRow() method Delete a row.

See also:

HTML Reference Manual:HTML <tr> Tag

Example

Example 1

Insert a new row at the first position of the table (and insert a <td> element with content):

// Find the <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the first position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the first and second positions of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add text to the new cell:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

Try it yourself

Example 2

Create and delete rows:

function myCreateFunction() {
  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";
}
function myDeleteFunction() {
  document.getElementById("myTable").deleteRow(0);
}

Try it yourself

Syntax

tableObject.insertRow(index)
Parameter Description
index

Required in Firefox and Opera, optional in IE, Chrome, and Safari.

Number, specifying the position of the line to be inserted (starting from 0). A value of 0 results in a new line being inserted at the first position.

You can also use the value -1, which will cause a new line to be inserted at the last position.

If this parameter is omitted, insertRow() inserts a new row at the last position in Chrome, IE, Firefox, and Opera, and at the first position in Safari.

Technical Details

Return Value: Inserted <tr> Element.

Browser Support

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