Search code examples
javascriptjqueryhtmljquery-selectorsjquery-calculation

How to move a "li" element to nth position from current on each click of a button?


How to move a "li" element to nth position from current on each click of a button?

In the below example, on each click of button, we have to move the 3rd li to 7th(3+4) position on 1st click, to 11th(7+4) position on 2nd click, to 15th(11+4) on 3rd and so on.

I've attached code snippet. And it is working for first click.

$(document).ready(function(){

$("button").on('click', function(){
  $(".active").insertAfter("li:nth-child(7)");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>move</button>
    <ul>
    <li>1st list item</li>
    <li>2nd list item</li>
    <li class="active">3rd list item</li>
    <li>4th list item</li>
    <li>5th list item</li>
    <li>6th list item</li>
    <li>7th list item</li>
    <li>8th list item</li>
    <li>9th list item</li>
    <li>10th list item</li>
    <li>11th list item</li>
    <li>12th list item</li>
    </ul>


Solution

  • This may be helpful

    $(document).ready(function(){
    var cnt=3;
    $("button").on('click', function(){
      cnt+=4;
      $(".active").insertAfter("li:nth-child("+cnt+")");
    });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>move</button>
        <ul>
        <li>1st list item</li>
        <li>2nd list item</li>
        <li class="active">3rd list item</li>
        <li>4th list item</li>
        <li>5th list item</li>
        <li>6th list item</li>
        <li>7th list item</li>
        <li>8th list item</li>
        <li>9th list item</li>
        <li>10th list item</li>
        <li>11th list item</li>
        <li>12th list item</li>
        </ul>