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 either JavaScript or jQuery?
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:
<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>
Adding the "sortable" class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
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/
$('.testWrapper').find('.test').sort(function (a, b) { return $(a).attr('data-percentage') - $(b).attr('data-percentage'); }) .appendTo('.testWrapper');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With