Eric Schoonover Eric Schoonover - 1 month ago 11
jQuery 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>

Answer
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);
});
Comments