jquery – How to add and remove elements from a div?

Question:

I want that when click the elements of #categoria they are not removed and added in #campoBusq . Also don't insert 2 times div that was already inserted.

jQuery(document).ready(function() {

    jQuery('#categoria').on('click','.elemento',function() {
      jQuery(this).appendTo('#campoBusq');
    });
    
    jQuery('#campoBusq').on('click','.elemento',function() {
      jQuery(this).appendTo('#categoria');
    });

});
 
#campoBusq {
border: 1px solid blue ;
width:45%;
float:left;
padding:5px;
height:200px;

}

#categoria {
border: 1px solid red;
width:45%;
padding:5px;
float:left;
height:200px;
}

.elemento {
border: 1px solid green;
width:90%;
margin:1%;
padding:1%;
float:left;
clear:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div id="campoBusq"></div>
  <div id="categoria">
    <div class="elemento">Chile</div>
    <div class="elemento">México</div>
    <div class="elemento">Perú</div>
    <div class="elemento">España</div>
    <div class="elemento">Argentina</div>
  </div>

Answer:

You can clone the item and then add it to it. Is this how you need it?

jQuery(document).ready(function() {

    jQuery('#categoria').on('click','.elemento',function() {
       var e = $(this).clone();
       var identificador = $(this).attr("iden");
       if($("#campoBusq").find("."+identificador).length){
         alert("Ya existe");
       }else{
         jQuery(e).appendTo('#campoBusq');
       } 
   });
    
    jQuery('#campoBusq').on('click','.elemento',function() {
       jQuery(this).remove();
    });

});
 
#campoBusq {
border: 1px solid blue ;
width:45%;
float:left;
padding:5px;
height:200px;

}

#categoria {
border: 1px solid red;
width:45%;
padding:5px;
float:left;
height:200px;
}

.elemento {
border: 1px solid green;
width:90%;
margin:1%;
padding:1%;
float:left;
clear:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div id="campoBusq"></div>
  <div id="categoria">
    <div class="elemento 1" iden="1">Chile</div>
    <div class="elemento 2" iden="2">México</div>
    <div class="elemento 3" iden="3">Perú</div>
    <div class="elemento 4" iden="4">España</div>
    <div class="elemento 5" iden="5">Argentina</div>
  </div>

EDIT There are many ways to validate it, I recommend that you do it with the data attribute, but the same way I left it, it works. You add something like an identifier. Before adding the cloned element, you get that attribute and look for an attribute with a class equal to that attribute inside div # searchfield, so you can compare if it exists or not.

Scroll to Top