views:

108

answers:

3

Hello,

I am experimenting with jQuery lately, and I was wondering if it's possible with js or pure jquery to reorder <li> elements. So if I have a silly list like the following:

<ul>
    <li>Foo</li>
    <li>Bar</li>
    <li>Cheese</li>
</ul>

How would I move the list elements around? Like put the list element with Cheese before the list element with Foo or move Foo to after Bar.

So is it possible?

If so, how?

Thanks!!

+1  A: 

Have a look at jquery ui sortable

http://jqueryui.com/demos/sortable/

Charlie boy
While very cool, I don't need the user to be able to resort, I just want to know if I can do it programmatically, either using jQuery or just javascript.
Alex
Aah I see! Didn't really get that from your question
Charlie boy
+1  A: 

something like this?

​var li = $('ul li').map(function(){
              return this;
         })​.get();
$('ul').html(li.sort());

demo

I was somewhat lost you may be wanting something like this...

$('ul#list li:first').appendTo('ul#list'); // make the first to be last...
$('ul#list li:first').after('ul#list li:eq(1)'); // make first as 2nd...
$('ul#list li:contains(Foo)').appendTo('ul#list'); // make the li that has Foo to be last...

more of it here1 and here2

Reigel
+1  A: 
var ul = $("ul");
var li = ul.children("li");

li.detach().sort();
ul.append(li);

This is a simple example where <li> nodes are sorted by in some default order. I'm calling detach to avoid removing any data/events associated with the li nodes.

You can pass a function to sort, and use a custom comparator to do the sorting as well.

li.detach.sort(function(a, b) {
   // use whatever comparison you want between DOM nodes a and b
});
Anurag