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

Solution 1:

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/

Solution 2:

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

Solution 3:

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);

Solution 4:

I think that the Tinysort Jquery plugin should be an option, you can get it i here: http://tinysort.sjeiti.com/

I did not tried it but the code should look like this:

$("#test > div").tsort("",{attr:"data-percentage"});

hope this will help