jquery – how to move all divs from one container to another by pressing a button?

Question:

I have the div with the id Branches and apart I have another empty div with the id selected what I need is to click the button to pasar all the div contained in Sucursales to seleccionadas

$("#pasar").click(function(){
    // ?????????
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="Sucursales">
    <div class="Sucursal">sucursal 1</div>
    <div class="Sucursal">sucursal 2</div>
    <div class="Sucursal">sucursal 3</div>
</div>
<div id="Seleccionadas">

</div>
<button id="Pasar"></button>

Answer:

The first thing is to select the divs that interest us, for example all the class items .Sucursal , or if you prefer all the divs that are direct children of #Sucursales .

elementos = $("#Sucursales > div");
// elementos = $("#Sucursales > .Sucursal"); // otra opción

And then they just need to be added to the destination container with appendTo () :

elementos.appendTo('#Seleccionadas');

However, if we also want them to keep all their associated events, detach () must first be called:

elementos = $("#Sucursales > div").detach();
elementos.appendTo('#Seleccionadas');

Code

$('#Pasar').on('click', function(){
    $("#Sucursales > div").detach()
                          .appendTo('#Seleccionadas');
});
#Sucursales {
    border: 1px solid green;
    min-height: 50px;
}

#Seleccionadas {
    border: 1px solid red;
    min-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="Sucursales">
    <div class="Sucursal">sucursal 1</div>
    <div class="Sucursal">sucursal 2</div>
    <div class="Sucursal">sucursal 3</div>
</div>
<button id="Pasar">Seleccionar</button>

<div id="Seleccionadas">

</div>
Scroll to Top