HTMLTableElement: insertRow()-Methode

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.

Die insertRow()-Methode des HTMLTableElement-Interfaces fügt eine neue Zeile (<tr>) in eine angegebene <table> ein und gibt eine Referenz auf die neue Zeile zurück.

Wenn eine Tabelle mehrere <tbody>-Elemente hat, wird die neue Zeile standardmäßig in das letzte <tbody> eingefügt. Um die Zeile in einen bestimmten Abschnitt einzufügen, verwenden Sie HTMLTableSectionElement.insertRow().

Note: insertRow() fügt die Zeile direkt in die Tabelle ein. Die Zeile muss nicht separat angehängt werden, wie es der Fall wäre, wenn Document.createElement() verwendet worden wäre, um das neue <tr>-Element zu erstellen.

Syntax

js
insertRow()
insertRow(index)

HTMLTableElement bezieht sich auf ein HTML-<table>-Element.

Parameter

index Optional

Der Zeilenindex der neuen Zeile. Wenn index -1 oder gleich der Anzahl der Zeilen ist, wird die Zeile als letzte Zeile angefügt. Wenn index weggelassen wird, ist der Standardwert -1.

Rückgabewert

Ein HTMLTableRowElement, das auf die neue Zeile verweist.

Ausnahmen

IndexSizeError DOMException

Wird ausgelöst, wenn index größer als die Anzahl der Zeilen ist.

Beispiele

Dieses Beispiel verwendet insertRow(-1), um eine neue Zeile in eine Tabelle einzufügen.

Wir verwenden dann HTMLTableRowElement.insertCell(), um eine neue Zelle in der neuen Zeile einzufügen. (Um gültiges HTML zu sein, muss ein <tr>-Element mindestens ein <td>-Element haben.) Schließlich fügen wir der Zelle mit Document.createTextNode() und Node.appendChild() Text hinzu.

HTML

html
<table id="my-table">
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>Row 3</td>
  </tr>
</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 ID
addRow("my-table");

Ergebnis

Spezifikationen

Specification
HTML
# dom-table-insertrow-dev

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
insertRow

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

Siehe auch