InsertRow vs. appendChild

Which method is preferred to add a row to the table?

var tr = tbl.insertRow (-1);

or

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

?

+7
javascript dom dhtml
source share
4 answers

insertRow will be much better. This is supported by class A browsers and a less detailed and cleaner API.

+5
source share

insertRow can be considered more reliable since it is a DOM [1].

The appendChild method appendChild consistently (albeit slightly) in all tested browsers (IE6 / 7, FF3, Chrome2, Opera9) when working outside the DOM, but when trying to change tables in a document (the more common one, try) much more slowly .

In other words: definitely use insertRow .


These tests were performed locally, so they can be unreliable, see the source here: http://pastie.org/482023

+3
source share

I see good arguments for insertRow, but I find one drawback: insertRow can only create a new empty string, while appendChild accepts an existing string object. With appendChild, you can move rows in a table, move a row from one table to another, or remove a row from a table and then return it (very convenient for paged tables). To do the same with insertRow (and insertCell), you have to pack the contents, create new rows and cells, and then add the old content to the new cells. Clumsy and seemingly less effective. Is there a more graceful way to do this? The insertRow option that accepts an existing row object will be nice.

+3
source share

If you use dom methods, tr should be added to the tbody, thead or tfoot element, not the table element.

0
source share

All Articles