Proj Something
  • Proj Blah
  • JQuery sort order base on #ID

    I have the following code:

    <ul>
    <li id="project_25">Proj Something</li>
    <li id="project_26">Proj Blah</li>
    <li id="project_27">Proj Else</li>
    <li id="project_31">Proj More</li>
    ...
    </ul>
    

    Is there a way to organize these LIs, rearrange them based on the LI identifier?

    Sort of:

    <ul>
    <li id="project_31">Proj More</li>
    <li id="project_27">Proj Else</li>
    <li id="project_26">Proj Blah</li>
    <li id="project_25">Proj Something</li>
    ...
    </ul>
    

    Thank.

    +3
    source share
    2 answers
    var arr = $('li').get();    
    arr.reverse();
    
    $.each(arr, function(i,v){
        $('ul').append(this);
    });
    
    +5
    source

    Please try the code below:

    var mylist = $('ul');
    var listitems = mylist.children('li').get();
    listitems.sort(function(a, b) {
       var compA = $(a).text().toUpperCase();
       var compB = $(b).text().toUpperCase();
       return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
    

    I found it here .

    NTN

    +2
    source

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


    All Articles