JQuery onClick Move this item to the beginning (like the first Child of UL)

OnClicking for any <li><a>....</a></li> element, except for the last child element, this element should be moved to the beginning as the first child <ul> element.


Fiddle


Description

Default:

 <ul> <li><a href="#">01</a></li> <li><a href="#">02</a></li> <li><a href="#">03</a></li> <li><a href="#">04</a></li> <li><a href="#">05</a></li> <li><a href="#">06 (Last Child)</a></li> </ul> 

If I click on 03 , this list should look like this.

 <ul> <li><a href="#">03</a></li> <li><a href="#">01</a></li> <li><a href="#">02</a></li> <li><a href="#">04</a></li> <li><a href="#">05</a></li> <li><a href="#">06 (Last Child)</a></li> </ul> 

But if you click on the last child <li> , this element should not be moved or resized ... the last child should always be the last.

+7
jquery
source share
3 answers

You can have a click event for the li element other than the last element using the $('li:not(:last)') element selector. and then use prependTo to add the parent as the first child:

 $('li:not(:last)').click(function(){ $(this).prependTo($(this).parent()); }); 

Working demo

Update: Multi-Elf Quest Solution

If for several UL elements you need to use :last-child instead of :last .As :last sets the last element in the matched set, whereas :last-child will target all li that are the last.

+5
source share

You can use the filter :not(:last) and jQuery prependTo :

 $('li a:not(:last)').click(function() { $li = $(this).parent('li'); $li.prependTo($li.parent('ul')); return false; }) 
+2
source share

Check the updated JSFiddle

This works as suggested. Just add jquery to your code

+1
source share

All Articles