jQuery - Select everything except a single elements and its children?

I'm trying to remove everything in the whole body, except of a single element and its children. How can I accomplish this?

Edit 1 Consider the following markup:

<html>
   <body>
      <div id="div1"></div>
      <div id="div2">
         <div id="elementNotToRemove"></div>
      </div>
      <div id="div3"></div>
      <div id="div4"></div>
   </body>
</html>

In the above example, I want to remove div1, div3 and div4, as well as their children, but conserve div2 because it contains the element not to remove.

Answers


 $("body > *").not("body > #elementtokeep").remove();

You can replace the not() part with whatever you want to keep


You can do it like this:

$('body > *:not(#dondelete)').remove();

Where your element has id="dondelete" and is a child of body.


This is an old question, but the accepted answer is wrong. It doesn't work in this situation (see http://jsfiddle.net/LVb3V/ ) and certainly not as a general solution.

Better to use:

$('body *').not('#div2, #div2 *').remove()‚Äč;

This will remove all elements in the body except for div2 and all the elements it contains.


Try

$('body > *:not(#123)').remove()

http://api.jquery.com/not-selector/


I think that

$("body *").not("body #div2")
           .not("body #div2 #elementtokeep")
           .not("body #div2 #elementtokeep *")
           .remove();

is the easiest way to focus it.

http://jsfiddle.net/6vb2va6g/


This code worked for me.

$('body > * :not(#123)').remove()

You need to give space between * and : . Earlier when try to use the code with

$('body > *:not(#123)').remove() it did not work. I had to give space between * and : character.

Happy coding.


Need Your Help

Liquibase or Flyway database migration alternative for Elasticsearch

java elasticsearch migration liquibase flyway

I am pretty new to ES. I have been trying to search for a db migration tool for long and I could not find one. I am wondering if anyone could help to point me to the right direction.

Finding the center of Leaflet polygon?

javascript php html leaflet

I have a bunch of leaflet polygons on a map I created. Each polygon represents something different. A specific set of information is displayed in a popup depending on the page the user is on. I nee...