W3cubDocs

/Web APIs

HTMLTableElement: insertRow() 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 insertRow() method of the HTMLTableElement interface inserts a new row (<tr>) in a given <table>, and returns a reference to the new row.

If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific section, use HTMLTableSectionElement.insertRow()

Note: insertRow() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element.

Syntax

insertRow()
insertRow(index)

HTMLTableElement is a reference to an HTML <table> element.

Parameters

index Optional

The row index of the new row. If index is -1 or equal to the number of rows, the row is appended as the last row. If index is omitted it defaults to -1.

Return value

An HTMLTableRowElement that references the new row.

Exceptions

IndexSizeError DOMException

Thrown if index is greater than the number of rows.

Examples

This example uses insertRow(-1) to append a new row to a table.

We then use HTMLTableRowElement.insertCell() 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) {
  // Get a reference to the table
  let tableRef = document.getElementById(tableID);

  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);

  // Insert a cell in the row at index 0
  let newCell = newRow.insertCell(0);

  // Append a text node to the cell
  let newText = document.createTextNode("New bottom row");
  newCell.appendChild(newText);
}

// Call addRow() with the table's ID
addRow("my-table");

Result

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Opera Safari Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet WebView Android WebView on iOS
insertRow 1 12
1Starting with Firefox 20, the index parameter has been made optional and defaults to -1 as per HTML specification.
10 4 18
4Starting with Firefox for Android 20, the index parameter has been made optional and defaults to -1 as per HTML specification.
10.1 3 1.0 4.4 3

See also

© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow