views:

437

answers:

4

Which method is preferred for adding a row to a table?

var tr = tbl.insertRow(-1);

or

var tr = document.createElement('tr'); tbl.appendChild(tr);

?

+4  A: 

insertRow would be the much better. It is supported by grade A browsers and it's less verbose and a cleaner API.

aleemb
Also, rows are not always children of table anyway, which makes the appendChild method more complex.
Rex M
@rex: what do you mean?
erikkallen
<tr> may be a child of a <tbody>, rather than a <table> element.
Rob
+2  A: 

insertRow might be argued as more reliable since it's DOM[1].

The appendChild method is consistently faster (albeit marginally) across all tested browsers (IE6/7, FF3, Chrome2, Opera9) when operating outside of the DOM, but when trying to modify tables within the document (a more common endeavour) it's significantly slower.

In other words: definitely use insertRow.


These tests were performed locally so may not be reliable, see the source here: http://pastie.org/482023

J-P
A: 

If you do use dom methods, a tr should be appended to a tbody, thead, or tfoot element, and not to a table element.

kennebec
A: 

I see good arguments for insertRow, but I find one disadvantage: insertRow can only create a new empty row, whereas appendChild takes an existing row object. With appendChild, you can move rows around in a table, move a row from one table to another, or take a row out of a table and later put it back in (very handy for paged tables). To do the same with insertRow (and insertCell), you would have to package up the contents, create new rows and cells, and then add the old contents to the new cells. Clumsy, and seemingly less efficient. Is there a more graceful way to do this? A variant of insertRow that takes an existing row object would be nice.

Andrew