drifterz28
10/25/2013 - 1:58 PM

Sort Dom objects, Not created by me.

Sort Dom objects, Not created by me.

function elmSort(selector, order, attr) {
    var listitems = selector;
    if(typeof attr === 'undefined'){
        attr = 'data-text';
        listitems.each(function(){
            var $this = $(this);
            $this.attr(attr, $this.text());
        });
    }
    listitems.sort(function (a, b) {
        var a = $(a).attr(attr),
            b = $(b).attr(attr),
            results;
        a = (!isNaN(+a)) ? +a : a;
        b = (!isNaN(+b)) ? +b : b;
        if (order === 'desc') {
            results = (a < b) ? 1 : 0;
        } else {
            results = (a > b) ? 1 : 0;
        }
        return results;
    });
    $.each(listitems, function (i, elem) {
        listitems.parent().append(elem);
    });
    return this;
}

elmSort($('#number li'), 'ase', 'data-number');

elmSort($('#alpha li'), 'desc');