Yogesh
Yogesh

Reputation: 331

select element and make it first element

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
</ul>

when I click on three I want it to be like:-

<ul>
    <li>Three</li>
    <li>One</li>
    <li>Two</li>
    <li>Four</li>
</ul>

Upvotes: 3

Views: 73

Answers (3)

Harsheet
Harsheet

Reputation: 628

You can try this

        $('#list li').on('click', function () {
            var index = $('li').index(this);
            if (index !== 0) {
                $(this).prependTo($(this).parent());
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <ul id="list" style="cursor: pointer;">
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
    </ul>
    </div>
    </form>
</body>
</html>

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 7004

handle click event with use of remove() and prepend() method.

$("body").on("click",'li',function(){
$('ul').prepend($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>

</ul>

Upvotes: 1

Dave L
Dave L

Reputation: 984

If you have jQuery you can use:

$('#items li').click(function() {
  $(this).parent().prepend(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id = "items">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

I can also write a non-jQuery one up if needed.

Upvotes: 5

Related Questions