tags:

views:

150

answers:

2

I have HTML page:

<head></head>
<body>
  <div>
    <div>
      <div id="myDiv">
      </div>
    </div>
  </div>
</body>

How to hide all divs, and just have the myDiv inside the body using jquery?

Update

The page may contain some other html elements such as some tables, anchors, p, and i just want to see the myDiv element.

+2  A: 

This should work:

$('div:not(#myDiv)').hide();  // hide everything that isn't #myDiv
$('#myDiv').appendTo('body');  // move #myDiv up to the body

Update:

If you want to hide EVERYTHING that, not just div elements, use this instead:

$('body > :not(#myDiv)').hide(); //hide all nodes directly under the body
$('#myDiv').appendTo('body');

Probably simpler is to wrap the entire "hideable" part of the page in a big container element, and hide that directly though.

Like so:

 <body>
     <div id="contents">
        <!-- a lot of other stuff here -->
        <div id="myDiv>
        </div>
     </div>
 </body>

Then you can just do this, which is cleaner and faster:

$('#contents').hide();
$('#myDiv').appendTo('body');
TM
what if the page contains some other elements, not all DIVs, for example some tables, links, and i just want to show the myDiv?
Amr ElGarhy
just on the topic of efficiency, it'd be *much* quicker to run `$("*").hide(); $("#myDiv").show();` compared to `$("*:not(#myDiv)")`
nickf
@nickf good point, although I've updated to something that should be faster than both of those options: `$('body > :not(#myDiv)').hide()`. Generally there aren't too many elements that are directly under the body element. Plus, as I mention in the answer, it's even better to just skip that nonsense and go for a wrapper element.
TM
A: 
$("div").each(function () { $(this).toggle(!!this.id); });

Note that this will explicitly show #myDiv. If you just want to hide the other divs:

$("div:not(#myDiv)").show();

Then you can do:

$("#myDiv").appendTo("body");
Anthony Mills