-2

This is what I'm doing to try to sort my <li> alphabetically, but for some reason, they are not in the correct order. I have a feeling it's because of the entire <li> tags in the items.push, but I was doing that to preserve the current classes and data attributes that the list item had. Is there a different way I can do this?

var items = [];

$("ul.cat-list li").each(function(){
     var liClass = $(this).attr("class");
     items.push("<li class="+liClass+" data-task="+$(this).data("task")+">"+$(this).html()+"</li>");
});

items.sort();

$("ul.alpha-list").html(items);
Jako
  • 4,731
  • 7
  • 39
  • 54

2 Answers2

2

It seems you want to clone the elements, you can use jQuery clone method and sort the elements based on their html content.

$('ul.cat-list li').clone().sort(function(a, b){
   return $.trim(a.innerHTML) > $.trim(b.innerHTML);
}).appendTo('ul.alpha-list');

http://jsfiddle.net/LmjTS/

Ram
  • 143,282
  • 16
  • 168
  • 197
0

Sort is set up for sorting lexicographical data, such as strings, and not DOM objects. It is possible to sort other types of data or objects with the jQuery sort command, but you need to use a sorting function.

A sorting function takes in two arguments, which are generally written as a and b by convention, and returns a boolean response based on those items. For this particular case, you want to sort by the inner HTML of your li items, so Adam > Bob, so we'll need a function like the following:

function mySort(a,b){
    return ( $(a).html() > $(b).html()) ? 1 :
      (a.html() < b.html()) ? -1 :
     0
}

So here he have a function that will return '1' if the content of a is lexicographically greater than b, '-1' if 'b' is greater, and 0 if they are either equal or cannot be sorted, assuming that I didn't make any errors. This function is then passed to sort as an argument, i.e. myArray.sort(mySort).

ckersch
  • 7,507
  • 2
  • 37
  • 44