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

Asked

Viewed 700 times

2

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

  • Sometimes there is no need to remove it, and you will add it again, using only Jquery’s Hide and show

2 answers

3


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

Example:

In the example below, the div yellow will be "deleted" from the added page within the div green at the click of buttons:

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>
<div id="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>

2

You can take 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 don’t know how efficient it is, but it works.

Browser other questions tagged

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