views:

53

answers:

3

Hello,

I would like to show and hide the divs that are just under body tag, not the ones which are under another div tag.

For example in the code below I'd like to hide with jquery div1 and div2, but not div1A, div1B, div2A and div2B. I know that if I hide div1 then div1A and div1B will be hidden.

<body>
   <div id="div1">
       <div id="div1A"></div>
       <div id="div1B"></div>
   </div>
   <div id="div2">
       <div id="div2A"></div>
       <div id="div2B"></div>       
   </div>
</body>

I need that because if I do $("div").hide(); and then $("div1").show(); div1A and div1B are still hidden because $("div").hide(); hide them, but $("div1").show(); doesn't affect them.

I tried with $("body div").hide(); but it had the same effect as $("div").hide();

I need a jquery call that only hides div1 and div2. Is there any way to do this without having to set a class name?

Thanks.

+10  A: 

This is a job for the immediate child selector: >

$('body > div').hide();
David Hedlund
For anyone finding this later, here's the best selector resource for questions like this: http://api.jquery.com/category/selectors/
Nick Craver
+2  A: 

Try this...

$("body > div").hide();

The '>' forces the selection to stop at only the direct div children of the body tag and won't delve down into the DOM to select all div elements.

Ryan
+2  A: 

$('body > div').hide(); is the way to go as others pointed out already but I just wanted to point out that using the children() method would also work, as that selects the immediate children of an element:

$('body').children('div');
Tatu Ulmanen