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 foll
$("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 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.
Try
$('body > *:not(#123)').remove()
http://api.jquery.com/not-selector/
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.
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/