Tutorials - HTML Table Add Row - DOM table methods

insertRow, insertCell, deleteRow

Overview

This page provides an overview of using the W3C DOM table methods. The methods covered in this tutorial are insertRow, insertCell, and deleteRow.

insertRow

For 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.

example

// given there are already at least 4 rows in the table
var newRow = yourTableObj.insertRow(4); // insert in the fifth row

references

insertCell

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.

example

// given there is already at least one cell in a row
var newCell = yourRowObj.insertCell(1); // insert a cell in the second column

references

deleteRow

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.

example

yourTableObj.deleteRow(0); // delete the first row

references

Example A

This example uses insertRow, insertCell, and innerHTML for the "Append", and it uses deleteRow for "Delete Last".

alligator
barracuda
chameleon

Example B

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.

Error:

Existing Row 1
Existing Row 2
Existing Row 3

Example Source

Public Domain

The JavaScript in tablebasics1.js is released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.

The JavaScript

The source for both Example A and Example B are in a plain text .js file

tablebasics1.js

Related mredkj.com Tutorials

  1. DOM table methods
  2. DOM - Refer to table cells
  3. innerHTML vs. DOM vs. cloneNode
  4. DOM Table Add Row
  5. DOM Table Delete Row
  6. DOM Table Delete Row - includes a calendar

For starters, I'd recommend [3], and if you've decided to use a DOM approach, then check out the simple examples of [1] and [2]. Then you could move on the extended examples in [4], [5], and [6]

About this page: