Search code examples
javascriptjquerydetach

how to get the information removed with detach?


I'm trying to remove an area of my website with detach because I have on mind to use it again, this is what I coding in the HTML

<div id="container">
 <p>Hello</p> 
</div>
<div id="containerShow"></div>

<a href="#" id="remove">Remove</a> | <a href="#" id="show">Show</a>

and this is my Jquery

$("#remove").click(function(){   
   $("#container").detach();
});

$("#show").click(function(){   
   $("#container").detach().appendTo("#containerShow");
});

What is supposed to do is remove the div container when click the link "Remove" and bring back that same information when click the link "Show" I know this look very simple, but the doc in jquery about detach is confused http://api.jquery.com/detach/ and I want a simple way to do it, I also found this post here How to I undo .detach()? but I don't make it work as I want.

My code remove my content fine, but I don't know how to get it back. Any help please ?


Solution

  • You have to hold it somewhere, i.e. in a variable:

    var element;
    
    $("#remove").click(function(){   
       element = $("#container").detach(); // detach and store in variable
    });
    
    $("#show").click(function(){   
       element.appendTo("#containerShow"); // restore stored element
    });