erikkallen
erikkallen

Reputation: 34401

insertRow vs. appendChild

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);

?

Upvotes: 8

Views: 7181

Answers (4)

Andrew
Andrew

Reputation: 5729

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.

Upvotes: 5

kennebec
kennebec

Reputation: 104780

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

Upvotes: 0

James
James

Reputation: 111920

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

Upvotes: 4

aleemb
aleemb

Reputation: 32085

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

Upvotes: 6

Related Questions