• <\/script>')

    Javascript / jQuery to sort alphabetically list with anchors

    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 sort this list in alphabetical order using anchor text, not li text. How to do it?

    I use this script to sort 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); }); } 
    +4
    source share
    3 answers

    try the following:

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

    You can use the sort method.

     $('#demoOne li').sort(function(a, b){ return $('a', a).text() > $('a', b).text() }).appendTo('#demoOne'); 

    http://jsfiddle.net/w3jfF/

    +5
    source

    You can use jQuery to get the whole li . Then use toArray to get your own javascript array. And you can sort the array using the sort method and provide a sort function to suit your needs.

    +1
    source

    Source: https://habr.com/ru/post/1446174/


    All Articles