Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLTableElement
  4. insertRow()

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.

Syntax

js
insertRow()insertRow(index)

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

Parameters

indexOptional

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

Return value

AnHTMLTableRowElement that references the newrow.

Exceptions

IndexSizeErrorDOMException

Thrown ifindex is 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

html
<table>  <tbody>    <tr>      <td>Row 1</td>    </tr>    <tr>      <td>Row 2</td>    </tr>    <tr>      <td>Row 3</td>    </tr>  </tbody></table>

JavaScript

js
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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp