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.

Upvotes: 19

Views: 26720

Answers (6)

Amit Mhaske
Amit Mhaske

Reputation: 471

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.

Upvotes: 1

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/

Upvotes: 0

ColBeseder
ColBeseder

Reputation: 3669

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.

Upvotes: 8

Michael L Watson
Michael L Watson

Reputation: 980

Try

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

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

Upvotes: 2

PiTheNumber
PiTheNumber

Reputation: 23562

You can do it like this:

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

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

Upvotes: 7

Philippe Leybaert
Philippe Leybaert

Reputation: 171914

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

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

Upvotes: 33

Related Questions