HTMLTableSectionElement: метод deleteRow()
Базовая реализация Широко доступна
Эта функция хорошо отработана и работает на многих устройствах и версиях браузеров. Она доступна во всех браузерах с июля 2015 года.
Метод deleteRow() интерфейса HTMLTableSectionElement удаляет определённую строку (<tr>) из заданного <section>.
Синтаксис
deleteRow(index)
Параметры
index-
index— целое число, представляющее строку, которая должна быть удалена. Однако, специальный индекс-1может использоваться для удаления последней строки раздела.
Возвращаемое значение
None (undefined).
Исключения
-
IndexSizeErrorDOMException -
Выбрасывается, если
indexбольше или равно количеству доступных строк или имеет отрицательное значение, отличное от-1.
Примеры
В этом примере две кнопки позволяют добавлять и удалять строки из раздела тела таблицы; также обновляется элемент <output> с количеством строк в таблице.
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
// 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();
});
Результат
Спецификации
| Спецификация |
|---|
| HTML # dom-tbody-deleterow |
Совместимость с браузерами
| Рабочие столы | Мобильные устройства | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox для Android | Opera Android | Safari на IOS | Samsung Internet | WebView Android | |
deleteRow |
1 | 12 | 1 | ≤12.1 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 | 4.4 |
См. также
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement/deleteRow