1

I want to sort the navigation menu with jQuery. The structure of nav menu is

<ul class="menu">
  <li class="item">
     <a class="link">one</a>
  </li>
  <li class="item">
     <a class="link">two</a>
  </li>
  <li class="item">
     <a class="link">three</a>
  </li>
  <li class="item">
     <a class="link">four</a>
  </li>
<ul>

I want to sort on the basis of the inner html of a tag. There is by default sort function in jquery. but it only sorts the strings. How I can sort the menu

Muhammad Usman
  • 10,426
  • 22
  • 72
  • 107
  • This link may help you http://stackoverflow.com/questions/304396/what-is-the-easiest-way-to-order-a-ul-ol-in-jquery – Konza Jan 29 '13 at 06:27
  • Its just about the `ul li`, but there is an anchor tag in my code. I have to order on basis of anchor tag – Muhammad Usman Jan 29 '13 at 06:29

2 Answers2

3
var items = $('.menu li').get();
items.sort(function(a,b){ 
  var keyA = $(a).find('a').text();
  var keyB = $(b).find('a').text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var ul = $('.menu');
ul.empty();
$.each(items, function(i, li){
  ul.append(li);
});

Sample

Anujith
  • 9,370
  • 6
  • 33
  • 48
1
var sortedList = jQuery('.menu > li').sort(function (a, b) {
    return (a.children[0].innerHTML > b.children[0].innerHTML) ? 1 : -1;
});

jQuery('.menu').html(sortedList);
Emil A.
  • 3,387
  • 4
  • 29
  • 46