MDN self-hosted library · e01.org

HTMLTableElement: insertRow() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

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>
js
function addRow(tableID) {
  // Get a reference to the table
  const tableRef = document.getElementById(tableID);

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

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

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

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