web api instance method
HTMLTableElement: insertRow() method
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 insertRow()
[!NOTE]
insertRow()inserts the row directly into the table. The row does not need to be appended separately as would be the case ifcreateElement()had been used to create the new<tr>element.
Syntax
insertRow()
insertRow(index)
HTMLTableElement is a reference to an HTML <table>
element.
Parameters
indexOptional- : The row index of the new row. If
indexis-1or equal to the number of rows, the row is appended as the last row. Ifindexis omitted it defaults to-1.
- : The row index of the new row. If
Return value
An HTMLTableRowElement that references the new
row.
Exceptions
IndexSizeErrorDOMException- : Thrown if
indexis greater than the number of rows.
- : Thrown if
Examples
This example uses insertRow(-1) to append a new row to a table.
We then use 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
createTextNode() and appendChild().
HTML
<table id="my-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 ID
addRow("my-table");