I\'m a bit out of my depth here and I\'m hoping this is actually possible.
I\'d like to be able to call a function that would sort all the items in my list alphabeti
Put the list in an array, use JavaScript's .sort()
, which is by default alphabetical, then convert the array back to a list.
http://www.w3schools.com/jsref/jsref_sort.asp
To make this work work with all browsers including Chrome you need to make the callback function of sort() return -1,0 or 1.
see http://inderpreetsingh.com/2010/12/01/chromes-javascript-sort-array-function-is-different-yet-proper/
function sortUL(selector) {
$(selector).children("li").sort(function(a, b) {
var upA = $(a).text().toUpperCase();
var upB = $(b).text().toUpperCase();
return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
}).appendTo(selector);
}
sortUL("ul.mylist");
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
improvement based on Jeetendra Chauhan's answer
$('ul.menu').each(function(){
$(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});
why i consider it an improvement:
using each
to support running on more than one ul
using children('li')
instead of ('ul li')
is important because we only want to process direct children and not descendants
using the arrow function (a,b)=>
just looks better (IE not supported)
using vanilla innerText
instead of $(a).text()
for speed improvement
using vanilla localeCompare
improves speed in case of equal elements (rare in real life usage)
using appendTo(this)
instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks