Dynamically add/remove element

BOTJr.

I am using jquery .remove function which removes elements from the DOM but what i was thinking is there any way to get back the deleted elements from the DOM.

<div id="parent" style="border: 1px solid red; padding: 10px;">
     I am the parent div.
     <div id="child" style="border: 1px solid green; padding: 10px;">
           I am a child div within the parent div.
     </div>
</div>
<p>&nbsp;</p>
<input type="button" value="Remove Element">

I have the above code.When the remove element button is clicked the .remove is used to remove the child element of the Div.Would it be possible using jquery to get back the elements that has been deleted without refreshing the whole page ?

Rajaprabhu Aravindasamy

You can remove and add an element by using .detach() like below,

//selector caching
var parent = $("#parent");

//removing the element and storing it in the parent's dataset
$(".remove").click(function() {
  if ($("#child").length) {
    parent.data("ref", $("#child").detach());
  }
});

//adding back the element by fetching it from the parent's dataset
$(".add").click(function() {
  var elem = parent.data("ref");
  if (elem.length) {
    parent.append(elem);
  }
});

DEMO

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related