JQuery sort()

JQuery. Write less, do more

JQuery. Write less, do more

Today I was trying to figure out how to sort a set of list item elements alphabetically using JQuery. Seems simple enough but after searching around I couldn’t find any ready made solution. The best I could find was JQuery Table Sort (which is a nice sorting package but not what I was looking for). After playing around for a bit, this is what I came up with:

UPDATE:
As Tom point out in the comments, beginning with jQuery 1.3.2 this can be further simplified to the following.

function sortAlpha(a,b){
    return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};

$('ol li').sort(sortAlpha).appendTo('ol');

Old code:

jQuery.fn.sort = function() {
   return this.pushStack( [].sort.apply( this, arguments ), []);
 };

function sortAlpha(a,b){
    return a.innerHTML > b.innerHTML ? 1 : -1;
};

$('ol li').sort(sortAlpha).appendTo('ol');

Short and sweet. The result is a in place sort based off the innerHTML alphabetically.

, , , ,