Andy Holmes
Andy Holmes

Reputation: 8077

sort UL & LI alphabetically

Morning everyone,

I have some code that sorts the direct LIs of a list i have, however i'd like it to sort the sublevels into alphabetical order too, however everything i have tried doesnt work, including adding the class to the sub levels - this just appends every LI to it, which is obviously wrong.

Could someone take a look at the code and give me a hand please? I'd be very grateful :)

http://codepen.io/andyjh07/pen/yetIq

Upvotes: 0

Views: 754

Answers (1)

Jai
Jai

Reputation: 74738

try this:

function firstLevel(){
  var mylist = $('ul.sort');
  var listitems = mylist.children('li').get();

  listitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  });
  $.each(listitems, function(idx, itm) { 
    mylist.append(itm); 
  });

  secLevel();
}

function secLevel(){
  var sublist = $('ul.sort li ul');
  var sublistitems = sublist.children('li').get();
  sublistitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  });
  $.each(sublistitems, function(idx, itm2) { 
    sublist.append(itm2); 
  });

}


$(document).ready(function() {
  firstLevel()
});

Upvotes: 1

Related Questions