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
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);
});
var sortedList = jQuery('.menu > li').sort(function (a, b) {
return (a.children[0].innerHTML > b.children[0].innerHTML) ? 1 : -1;
});
jQuery('.menu').html(sortedList);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.