HTMLTableSectionElement: deleteRow()-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 deleteRow()-Methode des HTMLTableSectionElement-Interfaces entfernt eine spezifische Zeile (<tr>) aus einem gegebenen <section>.

Syntax

js
deleteRow(index)

Parameter

index

index ist eine Ganzzahl, die die zu löschende Zeile angibt. Jedoch kann der spezielle Index -1 verwendet werden, um die letzte Zeile des Abschnitts zu entfernen.

Rückgabewert

Keiner (undefined).

Ausnahmen

IndexSizeError DOMException

Wird ausgelöst, wenn index größer oder gleich der Anzahl der verfügbaren Zeilen ist oder kleiner als -1, außer -1 selbst.

Beispiele

In diesem Beispiel ermöglichen zwei Schaltflächen das Hinzufügen und Entfernen von Zeilen aus dem Tabellenkörperabschnitt; es aktualisiert auch ein <output>-Element mit der Anzahl der aktuell in der Tabelle vorhandenen Zeilen.

HTML

html
<table>
  <thead>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
  </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

Specification
HTML
# dom-tbody-deleterow

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
deleteRow

Legend

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

Full support
Full support

Siehe auch