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.
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.
$("body > *").not("body > #elementtokeep").remove();
You can replace the not() part with whatever you want to keep
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.
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