What is the easiest way to order a <UL>/<OL> in jQuery?

I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order. Can anyone help?

Here is a sample list for people to work with:

<ul class="alphaList">
    <li>apples</li>
    <li>cats</li>
    <li>bears</li>
</ul>

Solution 1:

var items = $('.alphaList > li').get();
items.sort(function(a,b){
  var keyA = $(a).text();
  var keyB = $(b).text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var ul = $('.alphaList');
$.each(items, function(i, li){
  ul.append(li); /* This removes li from the old spot and moves it */
});

Solution 2:

Try this:

var elems = $('.alphalist li').detach().sort(function (a, b) {
  return ($(a).text() < $(b).text() ? -1 
        : $(a).text() > $(b).text() ? 1 : 0);
}); 
$('.alphalist').append(elems);

Solution 3:

For future googlers, I've found this plugin very useful. It has option to define character order for non-latin languages.

Older versions (jQuery dependent)

$('.submenu > li').tsort({
    charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'
});

For English only characters, no option is needed to define

$('.submenu > li').tsort();

Current version (jQuery independent) (29 March 2016)

Current version of tinysort is now independent from jQuery. Pure JavaScript. I updated jsfiddle for new version usage.

tinysort('.submenu > li', {
    charOrder: 'abcçdefgğhıijklmnoöprsştuüvyz'
});

Demo http://jsfiddle.net/ergec/EkScy/

Website http://tinysort.sjeiti.com/