Siwei Shen Siwei Shen - 5 months ago 24
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: http://jsfiddle.net/sg552sg552/Lsw6mnh4/15/
)

my html code is:

<table>
<thead>
<tr>
<th>string</th>
</tr>
</thead>
<tbody>
<tr>
<td>C</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td>A</td>
</tr>

</tbody>
</table>


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++) {
console.info("== before append, rows count: " + $(table).find('tr').size() )
// WHY doesn't this "append" increase the total tr size ?
table.append(rows[i]);
console.info("== 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.

Answer

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