Question

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>
 45  41769  45
1 Jan 1970

Solution

 100
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 */
});
2008-11-20

Solution

 8

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);
2016-10-25