HTMLTableSectionElement: insertRow() method
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{APIRef("HTML DOM")}}
The **insertRow()** method of the {{domxref("HTMLTableSectionElement")}} interface creates a {{HTMLElement("tr")}} element, inserts it at the specified position in the given table sectioning element ({{HTMLElement("thead")}}, {{HTMLElement("tfoot")}}, or {{HTMLElement("tbody")}}), and returns it.
This method creates and inserts the element directly, without requiring separate calls to methods such as {{domxref("Document.createElement()")}}, {{domxref("Node.insertBefore()")}}, and {{domxref("Node.appendChild()")}}.
Syntax
insertRow()
insertRow(index)Parameters
index{{optional_inline}}- : The index of the new row in the {{domxref("HTMLTableSectionElement.rows", "rows")}} collection. If
indexis-1or equal to the number of rows, the row is appended as the last row. Ifindexis omitted, it defaults to-1.
Return value
An {{domxref("HTMLTableRowElement")}} that references the new row.
Exceptions
IndexSizeError{{domxref("DOMException")}}- : Thrown if
indexis greater than the number of rows or smaller than-1.
Examples
In this example, two buttons allow you to add and remove rows from the table body section; it also updates an {{HTMLElement("output")}} element with the number of rows currently in the table.
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
// 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();
});Result
{{EmbedLiveSample("Examples", "100%", 175)}}
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- {{domxref("HTMLTableRowElement.insertCell()")}}
- {{domxref("HTMLTableElement.insertRow()")}}
- {{domxref("HTMLTableSectionElement.deleteRow()")}}