Swap div of place with jquery

Asked

Viewed 3,084 times

2

Let’s say I have one div Mom, and inside that div I have another 3. And a Button.

<div id="mae">
    <div id="a" class="child"></div>
    <div id="b" class="child"></div>
    <div id="c" class="child"></div>
</div>

<button id="Trocar">Trocar Div</div>

I would like then that when you click the button, the Divs change position! Indeed I would like the first div, to go last, and the next div to take the first position! And so on!

Ex :: Cliquei uma vez
    <div id="mae">        
        <div id="b" class="child"></div>
        <div id="c" class="child"></div>
        <div id="a" class="child"></div>
    </div>

Ex :: Cliquei duas vezes
    <div id="mae">
        <div id="c" class="child"></div>
        <div id="a" class="child"></div>
        <div id="b" class="child"></div>
    </div>

Ex :: Cliquei três vezes
    <div id="mae">        
        <div id="a" class="child"></div>
        <div id="b" class="child"></div>
        <div id="c" class="child"></div>
    </div>

As you can see! The cycle repeats again!

2 answers

3


$('#Trocar').click(function() {
    $('#mae div:first-child').remove().insertAfter($("#mae div:last"));
});

Full example:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$().ready(function() {

    $('#Trocar').click(function() {
        $('#mae div:first-child').remove().insertAfter($("#mae div:last"));
    });

});
</script>
</head>
<body>

<div id="mae">
    <div id="a" class="child">a</div>
    <div id="b" class="child">b</div>
    <div id="c" class="child">c</div>
</div>

<button id="Trocar">Trocar Div</div>

</body>
</html>

1

$('#Trocar').click(function() {
   $('#mae div:first-child').appendTo($('#mae'));
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.