How to remove an entire div in Jquery and then add it back?

2

How can I remove an entire div using .empty() or .remove() and then add it back to any function?

    
asked by anonymous 03.04.2018 / 04:54

2 answers

3

For this there is the method detach() . It has the same function as the remove() method, except that it saves the removed element to be inserted later.

Example:

In the example below, the% yellow% will be "deleted" from the page added within the% green% to the button click:

var div1;
function remover(){
   div1 = $("#div1").detach();
}

function inserir(){
   $("#div2").append(div1);
}
#div1{
   background: yellow;
   color: #000;
}
#div2{
   background: green;
   color: #fff;
   padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1">
   Olá!
</div>
<div id="div2">
   Mundo!
</div>
<br>
Clique em remover:
<button onclick="remover()" type="button">Remover</button>
<br>
Depois em inserir:
<button onclick="inserir()" type="button">Inserir</button>
    
03.04.2018 / 13:05
2

You can grab the content with .html (), store it in any string, remove it from the DOM, then recreate the DIV and fill it with .html (string). I do not know how efficient it is but it works.

    
03.04.2018 / 05:11