Qiao
Qiao

Reputation: 17049

Appending tr to table removes old tr?

I'm using this jQuery table sort
and I can't understand how it works

$('th').click(function(){
    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 tr, sort them and than append. But, where does it remove old unsorted tr?
It only append, but do not remove. What I am missing here?

Upvotes: 0

Views: 46

Answers (1)

Barmar
Barmar

Reputation: 781340

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.

Upvotes: 1

Related Questions