HTMLTableRowElement: метод insertCell()
Базовая Широко поддерживается
Эта функция хорошо отработана и работает на многих устройствах и версиях браузеров. Она доступна в браузерах с июля 2015 года.
Метод insertCell() интерфейса HTMLTableRowElement вставляет новую ячейку (<td>) в строку таблицы (<tr>) и возвращает ссылку на ячейку.
Примечание: insertCell() вставляет ячейку непосредственно в строку. Ячейка не требует отдельного добавления с помощью Node.appendChild(), как это было бы в случае, если бы новая <td> элемент была создана с помощью Document.createElement().
Вы не можете использовать insertCell() для создания нового <th> элемента.
Синтаксис
insertCell() insertCell(index)
Параметры
indexНеобязательно-
Индекс ячейки нового элемента. Если
indexравен или больше, чем количество ячеек, ячейка добавляется в качестве последней ячейки в строке. Еслиindexопущен, он по умолчанию равен-1.
Возвращаемое значение
Объект HTMLTableCellElement, ссылающийся на новую ячейку.
Исключения
-
IndexSizeErrorDOMException -
Выбрасывается, если
indexбольше, чем количество ячеек.
Примеры
В этом примере используется HTMLTableRowElement.insertCell() для добавления новой ячейки в строку.
HTML
<table>
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>C3</th>
<th>C4</th>
<th>C5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</tbody>
</table>
<button id="add">Add a cell</button>
<button id="remove">Remove last cell</button>
<div>This first row has <output>2</output> cell(s).</div>
JavaScript
// Obtain relevant interface elements
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // Select the first row of the body section
const cells = row.cells; // The collection is live, therefore always up-to-date
const cellNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateCellNumber() {
cellNumberDisplay.textContent = cells.length;
}
addButton.addEventListener("click", () => {
// Add a new cell at the end of the first row
const newCell = row.insertCell();
newCell.textContent = `Cell ${cells.length}`;
// Update the row counter
updateCellNumber();
});
removeButton.addEventListener("click", () => {
// Delete the row from the body
row.deleteCell(-1);
// Update the row counter
updateCellNumber();
});
Результат
Спецификации
| Спецификация |
|---|
| HTML # dom-tr-insertcell-dev |
Совместимость с браузерами
| Рабочий стол | Мобильные устройства | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox для Android | Opera Android | Safari на iOS | Samsung Internet | WebView Android | |
insertCell |
1 | 12 | 1 | ≤12.1 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 | 4.4 |
index_parameter_negative_one |
1 | 12 | 20 | ≤15 | 3 | 18 | 20 | ≤14 | 1 | 1.0 | 4.4 |
index_parameter_optional |
1 | 12 | 20 | 15 | 3 | 18 | 20 | 14 | 1 | 1.0 | 4.4 |
См. также
HTMLTableElement.insertRow()- Элемент HTML, представляющий ячейки:
HTMLTableCellElement
© 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/HTMLTableRowElement/insertCell