HTMLTableElement.insertRow()
The HTMLTableElement.insertRow()
method inserts a new row in the table.
Syntax
JavaScript
Copy Code
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.
Ifindex
is -1 or equal to the number of rows, the row is appended as the last row. Ifindex
is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1.- If a table has multiple
tbody
elements, by default, the new row is inserted into the lasttbody
. To insert the row into a specifictbody
:
Copy Codevar specific_tbody=document.getElementById(tbody_id);<br> var row=specific_tbody.insertRow(index)
Example
HTML
Copy Code
<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.
Specifications
Specification | Status | Comment |
---|---|---|
WHATWG 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. |
Recommendation | Specifies in more detail where the row is inserted. |
Document Object Model (DOM) Level 1 Specification The definition of 'HTMLTableElement.insertRow()' in that specification. |
Recommendation | Initial definition |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 4 | 3[1] | 5.5 | 10 | 4 |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | ? | ? | ? | ? |
[1] Starting with Gecko 20.0 (Firefox 20.0 / Thunderbird 20.0 / SeaMonkey 2.17) the index argument has been made optional and defaults to -1 as per HTML specification.
See also
License
© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/htmltableelement/insertrow