Alex Alex - 2 years ago 148
Javascript Question

reorder list elements - jQuery?

Is it possible to reorder

elements with JavaScript or pure jQuery. So if I have a silly list like the following:


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

Is it possible? If so, how?

Answer Source
var ul = $("ul");
var li = ul.children("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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download