Siwei Shen Siwei Shen - 3 months ago 12x
jQuery Question

Strange behavior on jQuery append() when sorting table

I was looking for a method to sort my very complex table, and found this approach which is working perfectly:

( completed code is here:

my html code is:



and my js code is:

$('th').click(function() {  
var table =  $(this).parents('table').eq(0);
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
for (var i = 0; i < rows.length; i++) {"== before append, rows count: " + $(table).find('tr').size() )
// WHY doesn't this "append" increase the total tr size ?
table.append(rows[i]);"== after append, rows count: " + $(table).find('tr').size() )

function comparer(index) {  
return function(a, b) {      
var valA = getCellValue(a, index),
valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ?  valA - valB  : valA.localeCompare(valB)  ;

function getCellValue(row, index) {
return $(row).children('td').eq(index).html();

The function( sorting the table) works perfectly, but I just wonder, why the "append()" function doesn't increase the "tr" count while there's no place to "remove" any "tr" ?

Thanks a lot.


From the jQuery append docs:

You can also select an element on the page and insert it into another:

$( ".container" ).append( $( "h2" ) );

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)

So the elements are really just being shuffled, not created/destroyed