Possible Duplicate:
Sort element by numerical value of data attribute
I want to reorganize divs according to a data attribute set on them, ranging from highest integer to lowest. Right now, I push all the data into an array and sort that but I'm not sure how to proceed. How can I use this to reorganize divs inside their parent div?
var prices = new Array();
$(this).children('.listing-item').each(function() {
var price = parseInt($(this).attr('data-listing-price'));
prices.push(price)
});
prices.sort(function(a,b){return b-a});
This gets me an array like 139,129,129,109,109,84 for example. Now my idea was to loop through the divs another time with a selector like this:
$('.listing-item[data-listing-price="' + prices[0] + '"]')
but I'm not sure how to move the divs (the div with the highest data-attribute integer should move to the top and so on. Any idea?
Here is the solution
HTML:
<div id="list">
<div class="listing-item" data-listing-price="2">2</div>
<div class="listing-item" data-listing-price="3">3</div>
<div class="listing-item" data-listing-price="1">1</div>
<div class="listing-item" data-listing-price="4">4</div>
</div>
JS:
var divList = $(".listing-item");
divList.sort(function(a, b){
return $(a).data("listing-price")-$(b).data("listing-price")
});
$("#list").html(divList);
JSFiddle:
http://jsfiddle.net/bittu4u4ever/ezYJh/1/
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