How can I sort elements by numerical value of data attribute?

前端 未结 5 984
清歌不尽
清歌不尽 2020-11-27 03:07

I have multiple elements with the attribute: data-percentage, is there a way of sorting the elements into ascending order with the lowest value first using eit

5条回答
  •  遥遥无期
    2020-11-27 03:28

    For some reason, on Firefox 64.0.2, none of the answers worked for me. This is what worked in the end, a mixture of Joseph Silber and Jeaf Gilbert's answers:

    var $wrapper = $('.testWrapper');
    
    $wrapper.find('.test').sort(function(a, b) {
        return +$(a).data('percentage') - +$(b).data('percentage');
    })
    .appendTo($wrapper);
    

提交回复
热议问题