I have three div
s and I want to sort them by height, from largest to smallest.
<div>smallest</div>
<div>largest</div>
<div>middle</div>
Any idea?
I have three div
s and I want to sort them by height, from largest to smallest.
<div>smallest</div>
<div>largest</div>
<div>middle</div>
Any idea?
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/
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');
I think http://james.padolsey.com/javascript/sorting-elements-with-jquery/ might provide you a good starting point.
I don't recall if jQuery will wrap the regular array object or not, but if not you can use a selector to get the divs and then use Array.sort(sortFunc) to sort them.
var divsToSort = $('div'); // I believe this returns an array object.
function sortByHeight(a, b) {
return $(a).height() - $(b).height();
}
divsToSort.sort(sortByHeight);
function sortNumber(a, b) {
return a - b;
}
$(function () {
var divOrder = [];
$.each($('div'), function () {
divOrder.push($(this).height());
});
var sortedByHeight = divOrder.sort(sortNumber);
for (i = 0; i < sortedByHeight.length; i++) {
$('div').eq(i).height(sortedByHeight[i]);
}
});
The html for this was:
<div style='border:solid 1px #ccc; width:100px; height:100px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:400px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:200px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:300px; float:left;'></div>