Javascript Reference - HTML DOM Table insertRow() Method








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

Browser Support

insertRow Yes Yes Yes Yes Yes

Syntax

tableObject.insertRow(index) 

Parameter Values

Value Description
index Required in Firefox and Opera, optional in IE, Chrome and Safari. A number to set the position starting at 0 of the row to insert .




Return Value

The inserted <tr> element.

Example

The following code shows how to insert new row(s) at the first position of a table.


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!-- w  w w . ja va2s  . com-->
    border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
  <tr>
    <td>Row2 cell1</td>
    <td>Row2 cell2</td>
  </tr>
</table>
<br>

<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    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";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to create and delete row(s).


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--from w  ww  .j ava2  s .c  om-->
    border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
  <tr>
    <td>Row2 cell1</td>
    <td>Row2 cell2</td>
  </tr>
</table>
<br>

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>

<script>
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);
}
</script>

</body>
</html>

The code above is rendered as follows: