Using jQuery's empty()
method, can I prevent a particular element from being removed from the DOM, while all other elements are removed?
For instance:
<div id="container">
<div id="noRemove"></div>
... more content ...
</div>
When I make this call with jQuery $("#container").empty()
, how can I prevent the removal of noRemove
while still removing the rest of the content inside container
?
Use the following, it will remove everything from the container but the element whose id
is noRemove
:
$('#container').contents().filter(function () {
return this.id != "noRemove";
}).remove();
DEMO.
You can't using the empty
function alone. Here's one way you could do it:
var $container = $('#container'),
$noRemove = $container.find('#noRemove');
$container.html($noRemove);
Here's a fiddle: http://jsfiddle.net/joplomacedo/R4cu5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With