Sort divs bases on element's data attribute

后端 未结 2 1787
独厮守ぢ
独厮守ぢ 2021-01-07 06:43

I need to be able to sort a list of divs based on the data-price attribute of a sub element. This is my markup:

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 07:18

    If you want to place them in the body, you could do this:

    function sorter(a, b) {
        return a.getAttribute('data-price') - b.getAttribute('data-price');
    };
    
    var sortedDivs = $(".terminal").toArray().sort(sorter);
    
    $(".container").remove(); //removing the old values
    
    $.each(sortedDivs, function (index, value) {
        $('body').append(value);   //adding them to the body
    });
    

    Living demo: http://jsfiddle.net/a2TzL/1/

提交回复
热议问题