sorting an ul list according to a li element with jquery?

后端 未结 1 520
执念已碎
执念已碎 2020-12-21 07:52

I\'m creating a horizontal list with < ul > element but what I want to do is to put each < ul > element in alphabetical order according to a < li > element. For exa

1条回答
  •  执笔经年
    2020-12-21 08:27

    WORKING DEMO

    $('.grid ul:gt(0)').each(function() {
        var txt1 = $(this).children('li:eq(1)').text();
        $(this).data('name', txt1);
    });
    
    var items = $('.grid ul');
    items.sort(function(a, b) {
        var chA = $(a).data('name');
        var chB = $(b).data('name');
        if (chA < chB) return -1;
        if (chA > chB) return 1;
        return 0;
    });
    var grid = $('.grid');
    $(grid).append(items);
    

    and the HTML

    • Name
    • Surname
    • Unit
    • City
    • John
    • Boe
    • B.A.
    • NY
    • Jane
    • Doe
    • M.A.
    • CA
    • Lin
    • Zyan
    • M.A.
    • OR
    • Matt
    • Albright
    • M.A.
    • CA

    Will result in:

    enter image description here

    How it works:
    We look for the text inside the desired li :eq()
    and we set this text as a jQuery .data() for each UL element.
    Than we just sort the ul by the retrieved .data() text - alphabetically!

    Happy coding!

    0 讨论(0)
提交回复
热议问题