jQuery - Sort a list alphabetically
William McKeehan
William McKeehan
February 3, 2022

jQuery - Sort a list alphabetically

jQuery - Sort a list alphabetically

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.

$(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();
    });

Source: http://stackoverflow.com/questions/13394796/javascript-jquery-to-sort…