How may I sort a list alphabetically using jQuery?
Something like this:
var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
Above code will sort your unordered list with id 'myUL'.
OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort
You do not need jQuery to do this...
function sortUnorderedList(ul, sortDescending) {
if(typeof ul == "string")
ul = document.getElementById(ul);
// Idiot-proof, remove if you want
if(!ul) {
alert("The UL object is null!");
return;
}
// Get the list items and setup an array for sorting
var lis = ul.getElementsByTagName("LI");
var vals = [];
// Populate the array
for(var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i].innerHTML);
// Sort it
vals.sort();
// Sometimes you gotta DESC
if(sortDescending)
vals.reverse();
// Change the list on the page
for(var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i];
}
Easy to use...
sortUnorderedList("ID_OF_LIST");
Live Demo →
$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
return ($(b).text()) < ($(a).text()) ? 1 : -1;
}
// decending sort
function dec_sort(a, b){
return ($(b).text()) > ($(a).text()) ? 1 : -1;
}
live demo : http://jsbin.com/eculis/876/edit