Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  103] [ 1]  / answers: 1 / hits: 66588  / 14 Years ago, wed, june 16, 2010, 12:00:00

Is it possible to reorder <li> elements with JavaScript or pure jQuery. 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.



Is it possible? If so, how?


More From » jquery

 Answers
16
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
});

[#96483] Sunday, June 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
;