The HTMLTableElement.insertRow() method 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 <tbody>:
let specific_tbody = document.getElementById(tbody_id);
let row = specific_tbody.insertRow(index);
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.
insertRow()
insertRow(index)
HTMLTableElement is a reference to an HTML <table> element.
An HTMLTableRowElement that references the new row.
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().
<table id="my-table">
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</table>
function addRow(tableID) {
let tableRef = document.getElementById(tableID);
let newRow = tableRef.insertRow(-1);
let newCell = newRow.insertCell(0);
let newText = document.createTextNode("New bottom row");
newCell.appendChild(newText);
}
addRow("my-table");