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>

Posted In: JavaScript, firefox, Internet Explorer

Commentary

Charles 2007-02-02 19:57:21

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

Administrator 2007-02-02 20:04:15

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.

David 2007-08-28 12:55:07

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

reginr 2007-10-24 08:18:12

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

lupo 2008-07-05 00:01:41

Thanks a lot! Worked perfectly!

Terence 2008-09-18 05:49:09

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