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

时间:2016-10-20 12:53:08

标签: javascript html css

$(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?

3 个答案:

答案 0 :(得分:3)

I think you are looking for .hide(); and .show();

$(document).ready(function(){
  $('#remove').click(function(){
    $('.test').hide();
  });
  $('#back').click(function(){
    $('.test').show();
  });
});
<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>

答案 1 :(得分:3)

Actually, you cannot restore any HTML tags that are removed by jquery function. Instead, to remove the elements without removing data and events you can use .detach() function.

答案 2 :(得分:1)

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

相关问题