Sort a list alphabetically using jQuery

$(function() { $.fn.sortList = function() { var mylist = $(this); var listitems = $('li', mylist).get(); listitems.sort(function(a, b) { var compA = $(a).text().toUpperCase(); var compB = $(b).text().toUpperCase(); return (compA < compB) ? -1 : 1; }); $.each(listitems, function(i, itm) { mylist.append(itm); }); } $("ul#demoOne").sortList(); });
On some cases, it can be very useful a sort a long list by alphabetical order.

This snippet take any list and order its element alphabetically.

#jquery #sort #alphabet #alphabetically


Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.