Dieser Inhalt wurde automatisch aus dem Englischen übersetzt, und kann Fehler enthalten. Erfahre mehr über dieses Experiment.

View in English Always switch to English

HTMLTableSectionElement: insertRow() Methode

Baseline Weitgehend verfügbar

Diese Funktion ist gut etabliert und funktioniert auf vielen Geräten und in vielen Browserversionen. Sie ist seit Juli 2015 browserübergreifend verfügbar.

Die insertRow() Methode des HTMLTableSectionElement Schnittstelle erstellt ein <tr>-Element, fügt es an der angegebenen Position im gegebenen Tabelle-Abschnittselement (<thead>, <tfoot> oder <tbody>) ein und gibt es zurück.

Diese Methode erstellt und fügt das Element direkt ein, ohne dass separate Aufrufe zu Methoden wie Document.createElement(), Node.insertBefore() und Node.appendChild() erforderlich sind.

Syntax

js
insertRow()
insertRow(index)

Parameter

index Optional

Der Index der neuen Zeile in der rows Sammlung. Wenn index -1 ist oder der Anzahl der Zeilen entspricht, wird die Zeile als letzte Zeile angehängt. 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 ist als die Anzahl der Zeilen oder kleiner als -1.

Beispiele

In diesem Beispiel ermöglichen zwei Schaltflächen, Zeilen im Tabellenkörper hinzuzufügen und zu entfernen; dabei wird auch ein <output>-Element mit der Anzahl der aktuell in der Tabelle vorhandenen Zeilen aktualisiert.

HTML

html
<table>
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>X</td>
      <td>Y</td>
      <td>Z</td>
    </tr>
  </tbody>
</table>
<button id="add">Add a row</button>
<button id="remove">Remove last row</button>
<div>This table's body has <output>1</output> row(s).</div>

JavaScript

js
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // The collection is live, therefore always up-to-date
const rowNumberDisplay = document.querySelectorAll("output")[0];

const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");

function updateRowNumber() {
  rowNumberDisplay.textContent = rows.length;
}

addButton.addEventListener("click", () => {
  // Add a new row at the end of the body
  const newRow = bodySection.insertRow();

  // Add cells inside the new row
  ["A", "B", "C"].forEach(
    (elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
  );

  // Update the row counter
  updateRowNumber();
});

removeButton.addEventListener("click", () => {
  // Delete the row from the body
  bodySection.deleteRow(-1);

  // Update the row counter
  updateRowNumber();
});

Ergebnis

Spezifikationen

Spezifikation
HTML
# dom-tbody-insertrow

Browser-Kompatibilität

Siehe auch