0

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?

Community
  • 1
  • 1
Qiao
  • 16,565
  • 29
  • 90
  • 117

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612