Possible Duplicate:
How may I sort a list alphabetically using jQuery?
I’m using jQuery to come to the rescue for a limited CMS setup.
I need to sort an ordered list alphabetically, but then I also need to be able to place “special” list items at the top of the list and sort again only those special items descending by their “optional” numerical value.
For example if this was my original markup:
<ul>
<li class=" ">C</li>
<li class=" ">A</li>
<li class=" ">B</li>
<li class=" ">E</li>
<li class=" ">D</li>
<li class="3">Z</li>
<li class="6">Y</li>
<li class="14">X</li>
</ul>
… I would want jQuery to sort it so this would be the resulting DOM content:
<ul>
<li class="14">X</li>
<li class="6">Y</li>
<li class="3">Z</li>
<li class=" ">A</li>
<li class=" ">B</li>
<li class=" ">C</li>
<li class=" ">D</li>
<li class=" ">E</li>
</ul>
If sorting by a class value is not possible or is overly convoluted, perhaps I could use the following markup structure instead:
<ul>
<li><span class="numerical">3</span><span class="alphabetical">B</span></li>
</ul>
Does anyone know what jQuery code would allow me to do this? Would I need to run a series of nested “each” actions and “insertAfter” and “insertBefore” functions that somehow compare values? I would think there is a better way, but I’m not sure where to begin my research.
I’m open to any and all suggestions. I’ll also be trying to figure this out on my own in the meantime, but I’m still a jQuery rookie so I doubt I’ll find the right code on my own 🙂
Thanks!!
You need a comparator function, and a way to rearrange the elements. Plugins are available which given the former will do the latter for you, although if the elements are the sole children of a single parent it’s pretty easy (see below).
For your comparator, you’ll need something which can be given a pair of your
<li>elements, and tell you which comes first:and for rearranging:
The
.eachloop works by just taking each sorted item, and adding it to the end of the<ul>– when there’s none left, it’s done.Shorter versions of the above are possible, e.g.:
See this jsfiddle