views:

129

answers:

4

The following code rearranges elements by the attribute "amount". How can I alter this code so the items will be reversed? Thanks.

var parent = $('#items');
var children = $('a', parent);
children.sort(function(a, b) {
    return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})

$.each(children, function(i, child) {
    parent.append(child);
});
A: 

Use prepend instead of append?

http://docs.jquery.com/Manipulation/prepend#content

idrumgood
+2  A: 

Change the order of the values you are comparing (b-a instead of a-b):

var children = $('a', parent).sort(function(a, b) {
    return parseInt($(b).attr('amount'), 10) - parseInt($(a).attr('amount'), 10);
});
Gumbo
Don't forget the radix parameter on parseInt, e.g. parseInt($(b).attr('amount'), 10)
Greg
`$.fn.sort` does not return an array, it returns the jQuery wrapped set again, which does not contain a `reverse` method.
Crescent Fresh
Thanks, the first example didn't work, the second did.
usertest
A: 
children.sort(function(a, b) {
    return parseInt($(a).attr('amount')) < parseInt($(b).attr('amount')) ? 0 : 1;
});
Kevin Peno
+1  A: 

I've used this technique. It's ideal for small collections.

jQuery.fn.reverse = function() {
   return this.pushStack(this.get().reverse(), arguments);
};

var r = $('.class').reverse();
spoulson