Callum Whyte
Callum Whyte

Reputation: 2429

jQuery re-order elements by tag

I am currently trying to re-order an unordered list of elements by their rel="1234" tag associated with each using jQuery.

However, my current code is causing the output not to appear and I cannot work out why. Can anyone help?

My jQuery code is:

$(function(){
    var elems = $('#test').children('li').remove();
    elems.sort(function(a,b){
        return parseInt(a.attr('rel')) > parseInt(b.attr('rel'));
    });
    $('#test').append(elems);
});

With basic mark-up like this:

<ul id="test">
    <li rel="4112">blub</li>
    <li rel="1422">blaaah</li>
    <li rel="6640">hmmmm</li>
    <li rel="2221">one more</li>
</ul>

http://jsfiddle.net/BQZHC/

Upvotes: 0

Views: 98

Answers (3)

Mat&#237;as C&#225;nepa
Mat&#237;as C&#225;nepa

Reputation: 5974

This is what you want

JS:

var elems = $('#test').children('li').remove();
elems.sort(function(a,b){
    return parseInt($(a).attr('rel'), 10) > parseInt($(b).attr('rel'), 10);
});
$('#test').html(elems);

Note that the "a" and "b" elements of your sort function shoud be treated as jQuery objects. Also you should specify the radix of the parseInt()

DEMO: http://jsfiddle.net/BQZHC/10/

Upvotes: 0

user2437417
user2437417

Reputation:

a and b are DOM elements, not jQuery objects.

Either wrap them with $() to make jQuery objects, or use getAttribute("rel") instead of .attr("rel"). It'ss a little longer, but requires less overhead.


Additionally, assuming you wanted a numeric ordering, I would use subtraction.

return a.getAttribute("rel") - b.getAttribute("rel");

There have been browsers in the past that have had issues with returning a boolean value.

Upvotes: 0

PSL
PSL

Reputation: 123739

Try this:-

$(function(){
    var elems = $('#test').children('li'); // You dont need to remove the elements
    elems.sort(function(a,b){
         return +$(a).attr('rel') > +$(b).attr('rel'); // use attr on jquery object i.e $(a), $(b)
    });
    $('#test').append(elems); // This will take care of repositioning the elements.
});

Demo

Upvotes: 1

Related Questions