Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 666
JayDee Avatar asked Jan 04 '13 16:01

JayDee


People also ask

How do you sort data in HTML?

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.

How do you select an element by data?

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.


2 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/

like image 126
Joseph Silber Avatar answered Sep 27 '22 21:09

Joseph Silber


$('.testWrapper').find('.test').sort(function (a, b) {    return $(a).attr('data-percentage') - $(b).attr('data-percentage'); }) .appendTo('.testWrapper'); 
like image 34
Jeaf Gilbert Avatar answered Sep 27 '22 22:09

Jeaf Gilbert