Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery reversing the order of child elements

Tags:

jquery

What is the best way to reverse the order of child elements with jQuery.

For example, if I start with:

<ul>   <li>A</li>   <li>B</li>   <li>C</li> </ul> 

I want to end up with this:

<ul>   <li>C</li>   <li>B</li>   <li>A</li> </ul> 
like image 984
tilleryj Avatar asked Mar 18 '11 03:03

tilleryj


2 Answers

var list = $('ul'); var listItems = list.children('li'); list.append(listItems.get().reverse()); 
like image 148
Anurag Avatar answered Sep 17 '22 21:09

Anurag


Edit: Anurag's answer is better than mine.

ul = $('#my-ul'); // your parent ul element ul.children().each(function(i,li){ul.prepend(li)}) 

If you call .prepend() on an object containing more than one element, the element being appended will be cloned for the additional target elements after the first, so be sure you're only selecting a single element.

like image 42
undefined Avatar answered Sep 19 '22 21:09

undefined