The HTMLTableElement.insertRow()
method inserts a new row in the table and returns a reference to the new row.
var row = HTMLTableElement.insertRow(optional index = -1);
HTMLTableElement
is a reference to a HTML table element.index
is the row index of the new row.row
is assigned a reference to the new row. A reference to HTMLTableRowElement.index
is -1 or equal to the number of rows, the row is appended as the last row. If index
is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1.tbody
elements, by default, the new row is inserted into the last tbody
. To insert the row into a specific tbody
:var specific_tbody=document.getElementById(tbody_id);
var row=specific_tbody.insertRow(index)
<table id="TableA"> <tr> <td>Old top row</td> </tr> </table> <script type="text/javascript"> function addRow(tableID) { // Get a reference to the table var tableRef = document.getElementById(tableID); // Insert a row in the table at row index 0 var newRow = tableRef.insertRow(0); // Insert a cell in the row at index 0 var newCell = newRow.insertCell(0); // Append a text node to the cell var newText = document.createTextNode('New top row'); newCell.appendChild(newText); } // Call addRow() with the ID of a table addRow('TableA'); </script>
To be valid in an HTML document, a TR must have at least one TD element.
Note that insertRow
inserts the row directly into the table and returns a reference to the new row. The row does not need to be appended separately as would be the case if document.createElement()
had been used to create the new TR element.
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'HTMLTableElement.insertRow()' in that specification. | Living Standard | |
Document Object Model (DOM) Level 2 HTML Specification The definition of 'HTMLTableElement.insertRow()' in that specification. | Obsolete | Specifies in more detail where the row is inserted. |
Document Object Model (DOM) Level 1 Specification The definition of 'HTMLTableElement.insertRow()' in that specification. | Obsolete | Initial definition |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 4 | Yes | 3
|
5.5 | 10 | 4 |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | ? | Yes | 4
|
Yes | Yes | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow