Javascript, Tables & InsertBefore

I was trying to dynamically add rows to a table and ran into a problem with both Firefox and Internet Explorer. I had a table with a couple rows of data and there was a link to add a new row at the bottom of the table (in its own row).

The javascript simply cloned the first row, cleaned out some values from the td’s and inserted the new row into the table before the last row (i.e., the inserted row would be the second to last row) . That’s where the problems arose. In firefox, table.appendChild(newRow) functioned fine, but when I tried table.insertBefore(newRow,lastRow) it threw a DOMexception saying it could not replace the child node because it didn’t exist. In Internet Explorer, I could use appendChild or insertBefore. It turns out, you need to append and or insert to the tbody html element, instead of the table element. A real basic example:

<html>
<body>
<table>
<tbody id=”useThis”>
<tr id=”row1″><td>Row One</td></tr>
<tr id=”row2″><td>Row Two</td></tr>
</tbody>
</table>
<script type=”text/javascript”>
//clone row1
var newRow = document.getElementById(’row1′).cloneNode(’true’);
//get row2
var row2 = document.getElementById(’row2′);
//add cloned row1 one before row2
document.getElementById(’useThis’).insertBefore(newRow,row2);
</script>
</body>
</html>

6 Responses to “Javascript, Tables & InsertBefore”

  1. Charles Says:

    it’ll be nice if anybody can give a solution for he above issue.
    i also faced a similar one and spending hours to fix it…

  2. Administrator Says:

    As I say above, you need to work on the tbody element of a table, not the table element itself. According to HTML specs, every table should have a tbody element.

  3. David Says:

    Many thanks! I was stuck with this for a long while too.

  4. reginr Says:

    Hey Robert!
    Thanks alot for posting I had the same problem :)
    thanks again!

  5. lupo Says:

    Thanks a lot! Worked perfectly!

  6. Terence Says:

    I have a similar problem on using insertBefore in Firefox. I am trying some code that it works on IE but it didn’t on Firefox any suggestions? Please help and thanks a lot

    function function1() {
    var myElement = document.createElement('’);
    document.all.myDiv.insertBefore(myElement);
    }

    Insert element

Leave a Reply