Question:
I have the div
with the id
Branches and apart from that I have another empty div
with the id
selected, what I need is to click on 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 items of class .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 target container with appendTo() :
elementos.appendTo('#Seleccionadas');
However, if we also want them to keep all of their associated events, detach() must be called first:
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>