Home » Jquery » Sort element by numerical value of data attribute

Sort element by numerical value of data attribute

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

HTML:

  <div class="testWrapper">
    <div class="test" data-percentage="30">
    <div class="test" data-percentage="62">
    <div class="test" data-percentage="11">
    <div class="test" data-percentage="43">
  </div>

Desired result:
HTML:

  <div class="testWrapper">
    <div class="test" data-percentage="11">
    <div class="test" data-percentage="30">
    <div class="test" data-percentage="43">
    <div class="test" data-percentage="62">
  </div>

using either Javascript or jQuery?

Answers:

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/

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

Questions:
Answers:

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