Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort DIVs by height?

I have three divs and I want to sort them by height, from largest to smallest.

<div>smallest</div>
<div>largest</div>
<div>middle</div>

Any idea?

like image 989
Andy Avatar asked Sep 25 '11 14:09

Andy


2 Answers

It's quite simple. Use .sort():

$('div').sort(function (a, b) {
    return $(a).height() > $(b).height() ? 1 : -1;  
}).appendTo('body');

Code: http://jsfiddle.net/fEdFt/2/

like image 75
Samich Avatar answered Nov 03 '22 22:11

Samich


Since jQuery returns an array, you can use the sort method on array to reorder the elements. Once they are sorted in the proper order, you can then remove them from the DOM and reinsert them in the order desired.

$('div.sortable').sort( function(a,b) {
   return $(b).height() - $(a).height();
}).appendTo('#container');
like image 34
tvanfosson Avatar answered Nov 03 '22 22:11

tvanfosson