Rohit Rohit - 29 days ago 8
CSS Question

how to restore HTML elements that are removed by jQuery's remove



$(document).ready(function()
{
$('#remove').click(function()
{
$('.test').remove();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-wraper">
<div class="test">
test
</div>
<div class="test2">
test2
</div>
</div>
<button id='remove'>Remove</button>
<button id='back'>Back</button>





I want to restore my
.test
div using jQuery, after I've removed it. How do I achieve this?

Answer

You can create a variable and before removing it store the dom in it.

$(document).ready(function(){
var cacheDom = "";
  $('#remove').click(function(){
        cacheDom = $('.test'); //storing the value in dom
    $('.test').remove();
  });
 $('#add').click(function(){
        $('.test3').append(cacheDom); // appending it back
  });
});

$(document).ready(function(){
var cacheDom = "";
  $('#remove').click(function(){
		 if ($('.test').length > 0) {
          cacheDom = $('.test');
          $('.test').remove();
        }
  });
 $('#add').click(function(){
		$('.test3').append(cacheDom);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-wraper">
<div class="test">
test
</div>
<div class="test2">
test2
</div>
</div>
<div class="test3"></div>
<button id='remove'>Remove</button>
<button id='add'>Add Back</button>

DEMO