Qiao Qiao - 1 year ago 89
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download