Empty () all but a specific item

Using jQuery's empty() method, can I prevent a specific item from being removed from the DOM, and all other items 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 noRemove from being deleted while keeping the rest of the contents inside the container ?

+4
source share
4 answers

You cannot use only the empty function. Here is one way to do this:

 var $container = $('#container'), $noRemove = $container.find('#noRemove'); $container.html($noRemove); 

Here's the script: http://jsfiddle.net/joplomacedo/R4cu5/

+10
source

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 .

+6
source

This is what I just used, which includes updating the table data after AJAX pull for a specific row. A bit of an answer.

 $('.overrideFcstRow td').each(function(){ if(!$(this).hasClass('overrideTitle')){ $(this).empty(); } }); 
+2
source

I think this should do the trick:

 $("#container").find(":not(#noRemove)").remove(); 
-1
source

All Articles