-1

I have a jQuery script to hide an element if it does not contain a certain element:

<script type="text/javascript"> 
$(document).ready(function(){
    $("div.main div p").not(":has(span)").css("display","none");
});
</script>

<div class="main">
    <div>
        <p>Hello <span>OK</span></p>
        <p>Hi</p>
    </div>
    <div>
        <p>Yo</p>
    </div>
</div>

This script would hide the <p>Hi</p> and the <p>Yo</p> text.

How can I check if the divs under div.main contain no <p> elements containing <span>, or another way: if all <p> elements under a div are set to display:none?... And set those divs to display:none.

So the HTML output would be:

<div>
    <p>Hello <span>OK</span></p>
    <p style="display:none">Hi</p>
</div>
<div style="display:none">
    <p style="display:none">Yo</p>
</div>

2 Answers 2

0

I think you can do it more simply:

$("div.main div p:not(:has(span)), div.main div:not(:has(p>span))").hide();

jsFiddle demo: http://jsfiddle.net/pdBbU/1/

0

One way would be to loop through the divs and check if they contain any p elements with spans. Something like the following would work:

$("div.main div").each(function(){
  if($(this).find("p:has(span)").length == 0){
    $(this).hide();
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.