Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 609
Mathias Lykkegaard Lorenzen Avatar asked Feb 07 '12 08:02

Mathias Lykkegaard Lorenzen


People also ask

How do you get the children of the $( this selector?

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.

How do you get children of children in jQuery?

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.

What does $( Div parent will select?

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.


2 Answers

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

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

like image 100
Philippe Leybaert Avatar answered Oct 21 '22 17:10

Philippe Leybaert


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.

like image 44
ColBeseder Avatar answered Oct 21 '22 17:10

ColBeseder