Javi
Javi

Reputation: 19789

show/hide first level divs with jquery

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.

Upvotes: 2

Views: 2505

Answers (3)

Ryan
Ryan

Reputation: 6866

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.

Upvotes: 2

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124828

$('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');

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129802

This is a job for the immediate child selector: >

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

Upvotes: 11

Related Questions