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>
February 2nd, 2007 at 11:57 am
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…
February 2nd, 2007 at 12:04 pm
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.
August 28th, 2007 at 5:55 am
Many thanks! I was stuck with this for a long while too.
October 24th, 2007 at 1:18 am
Hey Robert!
Thanks alot for posting I had the same problem
thanks again!
July 4th, 2008 at 5:01 pm
Thanks a lot! Worked perfectly!
September 17th, 2008 at 10:49 pm
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