tags:

views:

913

answers:

1

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>
+7  A: 
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);
});
Chatu