Alphabetically sort elements with jQuery

/**
 * Alphabetize elements.
 *
 * sort_container should be a jQuery object, like $(this) or $('ul')
 * sort_item should be a string, like '.form-item' or 'li'
 *
 * see also http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery#answer-1134983
 */
mukurtu.checkboxAlphaSort = function(sort_container, sort_item) {
  var list_items = sort_container.children(sort_item).get();
  list_items.sort(function(a, b) {
     return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
  });
  $.each(list_items, function(index, item) {
    sort_container.append(item);
  });
}

Leave a Reply