Tutorials - HTML Table Add Row - DOM table methods
insertRow, insertCell, deleteRow
This page provides an overview of using the W3C DOM table methods. The methods covered in this tutorial are insertRow, insertCell, and deleteRow.
insertRowFor a table, insert a row at the given index (base 0). An index value equal to the number of existing rows will append to the end. Also, in DOM Level 2 (which modern browsers support) an index value of -1 (negative one) will also append to the end.
// given there are already at least 4 rows in the table var newRow = yourTableObj.insertRow(4); // insert in the fifth row
For a row, insert a cell at the given index (base 0). An index value equal to the number of existing cells will append to the end. Also, in DOM Level 2 (which modern browsers support) an index value of -1 (negative one) will also append to the end.
// given there is already at least one cell in a row var newCell = yourRowObj.insertCell(1); // insert a cell in the second column
For a table, delete the row at the given index (base 0). In DOM Level 2 (which modern browsers support), if the index value is -1 (negative one) then the last row is deleted.
yourTableObj.deleteRow(0); // delete the first row
This example uses insertRow, insertCell, and innerHTML for the "Append", and it uses deleteRow for "Delete Last".
This uses the same methods as Example A, but also allows any value to be entered for the index to insert or delete, which means it has the potential to throw an error. That's why I wrapped the methods in a try/catch, then print out the error message.
For example, enter -2 for the Insert # and click the button. You'll get a different message depending on what browser you're using.
I'm using the try/catch for demonstration purposes, but the idea for a real implementation would be to validate the index before passing it in. FYI: Example A does a little bit of validation.
The source for both Example A and Example B are in a plain text .js file
Related mredkj.com Tutorials
- DOM table methods
- DOM - Refer to table cells
- innerHTML vs. DOM vs. cloneNode
- DOM Table Add Row
- DOM Table Delete Row
- DOM Table Delete Row - includes a calendar