Question

I'm sorting a list that looks something like this:

<ul class = "demoOne">
  <li><a href="http://somelink.com">Some text</a></li>
  <li><a href="http://somelink.com">Some more text</a>
     <ul>
        <li><a href="http://somelink.com">Some nested text</a></li>
        <li><a href="http://somelink.com">Some more nested Text</a></li>
        <li><a href="http://somelink.com">Even more nested Text</a></li>
     </ul>
  </li>
  <li><a href="http://somelink.com">Still more text</a></li>
  <li><a href="http://somelink.com">Even more text</a></li>
</ul>

I found this solution on another question:

$(function() {
    $.fn.sortList = function() {
    var mylist = $(this);
    var listitems = $('li', mylist).get();
    listitems.sort(function(a, b) {
        var compA = $(a).text().toUpperCase();
        var compB = $(b).text().toUpperCase();
        return (compA < compB) ? -1 : 1;
    });
    $.each(listitems, function(i, itm) {
        mylist.append(itm);
    });
   }

    $("ul#demoOne").sortList();

});

The problem that I'm having is that this takes all of my nested links and inserts them into the outer list.

So what I end up with is a list that looks like this:

  • Even more nested text
  • Even more text
  • Some more nested text
  • Some nested text
  • Some more text
  • Some text
  • Still more text

How can I fix this?

I'm just learning jQuery and totally out of my depth here, so please go easy.

Was it helpful?

Solution

It feels a bit hacky to me, but the way I ended up doing it is to add a sortable class to the parent li's.

<ul class = "demoOne">
  <li class="sortable"><a href="http://somelink.com">Some text</a></li>
  <li class="sortable"><a href="http://somelink.com">Some more text</a>
     <ul>
        <li><a href="http://somelink.com">Some nested text</a></li>
        <li><a href="http://somelink.com">Some more nested Text</a></li>
        <li><a href="http://somelink.com">Even more nested Text</a></li>
     </ul>
  </li>
  <li class="sortable"><a href="http://somelink.com">Still more text</a></li>
  <li class="sortable"><a href="http://somelink.com">Even more text</a></li>
</ul>

Then I grabbed and sorted those li's by class name.

$('.sortable').not(".sortable li").sort(function(a, b){
        return $('a', a).text() > $('a', b).text();
    }).appendTo(".current");

I would still love to see a way to do this without the use of an additional class. If anybody knows a way to do that I'd gladly take this answer down and accept that as a better answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top