Qiao Qiao - 4 months ago 51
jQuery Question

Appending tr to table removes old tr?

I'm using this jQuery table sort

and I can't understand how it works

var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
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() }

So, it takes all
, sort them and than
. But, where does it remove old unsorted

It only
, but do not
. What I am missing here?


A DOM element can only be in one place at a time. When you append an existing element to a new place in the DOM, it doesn't make a copy of it, it moves the element to the new location, thus removing it from the old place.