Javascript/JQuery to sort alphabetically a list with anchors

anchor, javascript, jquery, sorting

Solution

try this:

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

});

Problem

I have this list: ``` <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Dhenie fotokopje aktesh nga dosja 12</a></li> <li><a href='http://site/Service.aspx?shId=1155'>Depozitim kerkesash Ankimore/Rekurse kunder vendimeve civile/penale 12</a></li> <li><a href='http://site/Service.aspx?shId=1156'>Dhenie Vendimesh12</a></li> <li><a href='http://site/Service.aspx?shId=1157'>Integrimi i Ish te Perndjekurve Polikite 12</a> </li> <li><a href='http://site/Service.aspx?shId=1158'>Dhenie Drejtesie</a></li> <li><a href='http://site/Service.aspx?shId=1159'>Gjykata e Rrethit Gjyqësor Lezhë ushtron juridiksionin gjyqësor civil dhe penal në territorin e qarkut Lezhë të Republikës së Shqipërisë.</a></li> </ul> ``` I want to alphabetically sort this list, using the anchor text, not the li text. How to do that? I'm using this script to sort them by li text ``` function sortUnorderedList(ul, sortDescending) { var items = $('.demo 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 keyA = $(a).text(); var keyB = $(b).text(); if (keyA < keyB) return -1; if (keyA > keyB) return 1; return 0; }); var ul = $('.demo'); $.each(items, function(i, li){ ul.append(li); }); } ```

Original source