ababa
ababa

Reputation: 1873

How to sort divs according to their id using jQuery?

I have a set of divs with random ids:

<div id="container">
   <div id="2"></div>
   <div id="9"></div>
   <div id="7"></div>
   <div id="1"></div>
   <div id="4"></div>
</div>

Is there a fast way to sort them according to their id values using jQuery? Thank you.

Upvotes: 9

Views: 19711

Answers (3)

Wikser
Wikser

Reputation: 820

I'd use the tinysort plugin:

http://tinysort.sjeiti.com/

In your case it would be something like:

$("#container > div").tsort("",{attr:"id"});

Upvotes: 20

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93193

Try my jquery plugin $.toArrayouter, using Underscore library.

$('#container').html(_.sortBy($('#container>div').toArrayouter(),function (name) {return name} ).join(''))

Demo : http://jsfiddle.net/abdennour/fDZjR/1/

Upvotes: 0

LBushkin
LBushkin

Reputation: 131676

There are plugins and the like to do sorting of elements. If you plan on actually re-ordering the DOM elements, you should probably use one of them.

If you just want a sorted list of the divs, you can use Javascript - since arrays can be sorted using a custom comparison function. You can convert the selected set of <div>s into an array using toArray() and then sort them using this mechanism.

$('#container > div').toArray().sort( function(a,b) { a.id - b.id } );

You could also use the detach() and appendTo() method to remove and the re-insert the elements in sorted order. However, this may not be the most efficient way to re-order the DOM elements.

Upvotes: 8

Related Questions