tags:

views:

39

answers:

2

Hi all,

I was wondering how I could hide a div if the child div doesn't exist inside it. Each div will contain a h2 tag, but if the div doesn't include a div named "info" I'd like it to be hidden. Here's the structure:

<div class="qaContainer"> (this div can stay as is, as it contains an "info" div)
  <h2>Testing Category 03</h2>
  <div class="info">if this div exists then this parent div can stay as is</div>
</div>
<div class="qaContainer"> (i need this div to be hidden as it doesn't contain a "info" div) 
  <h2>Testing Category 04</h2>
</div>

Cheers

+3  A: 

An obvious solution could be

$('.qaContainer').each(function() {
   $(this)[0 == $(this).find('.info').size() ? 'hide' : 'show']();
});

** EDIT **

The solution is obvious because it's not using fancy selectors or conditionals; it just finds every desired elements (here, any elements with class 'qaContainer') and loop over them. In the loop's callback function, hide or show the element currently being iterated depending on if there's a child element with a CSS class 'info'. This solution will hide or show the elements, so it is generic and reusable; just execute these three lines whenever the DOM changes and you want to update your 'qaContainer' elements.

Yanick Rochon
+1. Although this works, I think it'd be a little more helpful to explain why it's an "obvious solution".
Jim Schubert
alright, solution edited :)
Yanick Rochon
It's a really interesting solution (although as someone who works with CSS more I usually find selectors more intuitive). I think `.length` would be better than calling a function.
Yi Jiang
+2  A: 

I'm guessing something like

$('.qaContainer').not($('.info').parent()).hide();

Would work.

Yi Jiang