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.
TheinsertRow() method of theHTMLTableElement interface inserts a new row(<tr>) in a given<table>, and returns a reference tothe new row.
If a table has multiple<tbody> elements, by default, the new row isinserted into the last<tbody>.To insert the row into a specific section, useHTMLTableSectionElement.insertRow()
Note:insertRow() inserts the row directly into thetable. The row does not need to be appended separately as would be the case ifDocument.createElement() had been used to create the new<tr> element.
In this article
Syntax
insertRow()insertRow(index)HTMLTableElement is a reference to an HTML<table>element.
Parameters
indexOptionalThe row index of the new row. If
indexis-1or equal tothe number of rows, the row is appended as the last row.Ifindexis omitted it defaults to-1.
Return value
AnHTMLTableRowElement that references the newrow.
Exceptions
IndexSizeErrorDOMExceptionThrown if
indexis greater than the number of rows.
Examples
This example usesinsertRow(-1) to append a new row to a table.
We then useHTMLTableRowElement.insertCell() to insert a new cell in thenew row. (To be valid HTML, a<tr> must have at least one<td> element.) Finally, we add some text to the cell usingDocument.createTextNode() andNode.appendChild().
HTML
<table> <tbody> <tr> <td>Row 1</td> </tr> <tr> <td>Row 2</td> </tr> <tr> <td>Row 3</td> </tr> </tbody></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 IDaddRow("my-table");Result
Specifications
| Specification |
|---|
| HTML> # dom-table-insertrow-dev> |