Sort divs bases on element's data attribute

后端 未结 2 1766
独厮守ぢ
独厮守ぢ 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:05

    the following should work:

    $('.container').sort(function (a, b) {
      return $(a).find('.terminal').data('price') - $(b).find('.terminal').data('price');
    }).each(function (_, container) {
      $(container).parent().append(container);
    });
    

    though I recommend against doing this without a common parent. The $(container).parent().append(container); part could be problematic if there are other child nodes present.

    demo: http://jsbin.com/UHeFEYA/1/


    alternatively you could do this:

    $('.terminal').sort(function (a, b) {
      return $(a).data('price') - $(b).data('price');
    }).map(function () {
      return $(this).closest('.container');
    }).each(function (_, container) {
      $(container).parent().append(container);
    });
    
    0 讨论(0)
  • 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/

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