jQuery.sortItems

A much-requested on SO function for sorting DOM elements.

jQuery.fn.sortItems = function (key) {
    var $items = [],
        $wrap = $('<div/>'),
        i, l;
    this.each(function () {
        $items.push([key(this), $(this)]);
    });
    if (!$items) {
        return;
    }
    $wrap.insertBefore($items[0][1]);
    $items.sort();
    for (l = $items.length, i = l - 1; i >= 0; i--) {
        $items[i][1].insertAfter($wrap);
    }
    $wrap.remove();        
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
jQuery.fn.sortItems = function (key) {
    var $items = [],
        $wrap = $('<div/>'),
        i, l;
    this.each(function () {
        $items.push([key(this), $(this)]);
    });
    if (!$items) {
        return;
    }
    $wrap.insertBefore($items[0][1]);
    $items.sort();
    for (l = $items.length, i = l - 1; i >= 0; i--) {
        $items[i][1].insertAfter($wrap);
    }
    $wrap.remove();        
};

Demo.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.