getButterfly Logo getButterfly

A recent project of mine required sorting an existing ul/li list. The only way to do it, without interacting with the PHP code was a jQuery snippet. See it below (there is no additional information or documentation available).

// Sort destinations alphabetically // Ciprian
$(window).on('load', function(){
    var groupedLiElements = $('#destinations .list:nth-child(1) ul.grouped').children('li').length;
    for(i=0; i<groupedLiElements; i++) {
        var items = $('#destinations .list:nth-child(1) ul.grouped li:nth-child(' + i + ') ul li').get();
        items.sort(function(a,b){
            var keyA = $(a).text();
            var keyB = $(b).text();

            if(keyA < keyB) return -1;
            if(keyA > keyB) return 1;
            return 0;
        });
        var ul = $('#destinations .list:nth-child(1) ul.grouped li:nth-child(' + i + ') ul');
        $.each(items, function(i, li){
            ul.append(li);
        });
    }

    var items = $('#destinations .list:nth-child(2) ul.simple li').get();
    items.sort(function(a,b){
        var keyA = $(a).text();
        var keyB = $(b).text();

        if(keyA < keyB) return -1;
        if(keyA > keyB) return 1;
        return 0;
    });
    var ul = $('#destinations .list:nth-child(2) ul.simple');
    $.each(items, function(i, li){
       ul.append(li);
    });

    var items = $('#destinations .list:nth-child(3) ul.simple > li').get();
    items.sort(function(a,b){
        var keyA = $(a).text();
        var keyB = $(b).text();

        if(keyA < keyB) return -1;
        if(keyA > keyB) return 1;
        return 0;
    });
    var ul = $('#destinations .list:nth-child(3) ul.simple');
    $.each(items, function(i, li){
        ul.append(li);
    });
});

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply