Reddy
Reddy

Reputation: 1497

jQuery onClick Move this element to top (as first Child of UL)

OnClicking on any <li><a>....</a></li> element except last child, this element should be moved to top as first child of <ul>.


FIDDLE


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.

Upvotes: 8

Views: 3686

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82241

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.

Upvotes: 8

Amar Kamthe
Amar Kamthe

Reputation: 2582

Check this updated JSFiddle

This works as per suggested. Just add the jquery to your code

Upvotes: 1

Jake Opena
Jake Opena

Reputation: 1525

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

Upvotes: 2

Related Questions