1

So i have something linke that:

<ul id="list">
<li class="item">
<a>
<span class="name> name1 </span>
</a>
<a>
<span class="name> name2 </span>
</a>
<a>
<span class="name> name3 </span>
</a>
</li>
</ul>

how can i sort this list by the name alphabeticaly?

kind regards

Jon Egerton
  • 40,401
  • 11
  • 97
  • 129
  • 1
    > - http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery – Luca Filosofi Nov 30 '11 at 23:11
  • How is the list built? Is it all client-side? Can you do the sorting on the server-side before the list is rendered? Is it a static list? – Cᴏʀʏ Nov 30 '11 at 23:12
  • @aSeptik: He wants to sort by a class name within a span within an anchor. Your example is good for reference but isn't a solution for this question. – Cᴏʀʏ Nov 30 '11 at 23:14

3 Answers3

3

Try this plugin:

http://james.padolsey.com/javascript/sorting-elements-with-jquery/

using a custom comparator, something like this:

$('li').sortElements(function(a, b){
    return $(a).find('.name').text() > $(b).find('.name').text() ? 1 : -1;
});
Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
  • People are pretty fast with google lol. I came up with that exact link and was just typing an answer when I realized someone has answered already haha. – MSI Nov 30 '11 at 23:13
  • For those wondering before testing, this works exactly as advertised. js file is available here: https://github.com/padolsey-archive/jquery.fn/tree/master/sortElements – user1063287 Sep 03 '16 at 11:45
  • 1
    PS It wasn't case insensitive for me however, so for example `Xylophone` would appear before `rlink` in a list, I chained `.toLowerCase()` to both instances of `text()` and it appears to be working. – user1063287 Sep 03 '16 at 13:23
1

For simple cases, you don't even need a plugin. This code worked for me to sort a list of links:

function sortAlpha(a,b){
    return $(a).find('a').text().toLowerCase() > $(b).find('a').text().toLowerCase() ? 1 : -1;
};

$('#thelist li').sort(sortAlpha).appendTo('#thelist');

No need for span tags with this method.

(the basic idea isn't my own, I copied it from somewhere, but don't remember where from.)

Tom
  • 2,688
  • 3
  • 29
  • 53
1
$(function() {
    var names = elements = [];
    $('.item .name').each(function(i, item) {
        var name = $.trim($(this).text()) + '_' + i;
        names[i] = name;
        elements[name] = $(this).parent().remove().clone();
    });
    $.each(names.sort(),function(i, item) {
        $('.item').append(elements[item]);
    });
});
Luca Filosofi
  • 30,905
  • 9
  • 70
  • 77