OnClicking on any <li><a>....</a></li>
element except last child, this element should be moved to top as first child of <ul>
.
Description
By 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 become as below..
<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 Click on last child <li>
this element should not be moved or changed... last child should remain as last always.
The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).
The jQuery:first-child selector is used to selects all elements that are the first child of its parent. The jQuery:first-child selector is a built-in selector which is used on the HTML element. The first-child selector is similar to :nth-child(1), while the . first() method selects only single element.
To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.
The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.
You can have a click event for li element except last element using $('li:not(:last)')
element selector. and then use prependTo for appending as first child to parent:
$('li:not(:last)').click(function(){
$(this).prependTo($(this).parent());
});
Working Demo
Update: Solution for targetting multiple UL elments
In case for multiple UL elements, you need to use :last-child
instead of :last
.As :last
targets last element in matched set whereas :last-child
will target all li that are last child.
You can use :not(:last)
filter and jQuery prependTo
:
$('li a:not(:last)').click(function() {
$li = $(this).parent('li');
$li.prependTo($li.parent('ul'));
return false;
})
Check this updated JSFiddle
This works as per suggested. Just add the jquery
to your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With