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

前端 未结 5 996
清歌不尽
清歌不尽 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:18

    Use Array.sort:

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

    Here's the fiddle: http://jsfiddle.net/UdvDD/


    If you're using IE < 10, you can't use the dataset property. Use getAttribute instead:

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

    Here's the fiddle: http://jsfiddle.net/UdvDD/1/

提交回复
热议问题