skip to Main Content

HTML:

<div class="div1">
    <div class="child1">Some text</div>
    <div class="child2">Some text</div>
    <div class="child3"><img src="#" /></div>
</div>

<div class="div2">...</div> <!-- I want to hide .div2 -->

CSS:

.div1 {  }

.child1 { display: none }
.child2 { display: block }
.child3 { display: none }

.div2 {  }

How to hide .div2 when what is left to display in .div1 is a text and not an img?

Tried this but doesn’t work:

if ($(".div1:not(img)").length) { 
$(".div2").hide(); }) 

3

Answers


  1. I hope this is what you are looking for

    $('.div1 > div').each(function(){
        if($(this).is(':visible') && $(this).find('img').length>0){
        $('.div2').show();
        }
        else{
        $('.div2').hide();
      }
    })
    .child1 { display: none }
    .child2 { display: block }
    .child3 { display: none }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="div1">
        <div class="child1">Some text</div>
        <div class="child2">Some text</div>
        <div class="child3"><img src="#" /></div>
    </div>
    
    <div class="div2">...</div> <!-- I want to hide .div2 -->
    Login or Signup to reply.
  2. Get the image element lenght of div1

    Get the length of the image whose parent div has display:none property.

    If both are equal then hide the other div [div2].

    Working snippet:

    var Div1ImgCount = $('.div1').find('img').length;
    var Div1ImgNotDisplayCount = $('.div1').find('img').filter(function() {
        return $(this).closest('div').css('display') == 'none';
    }).length;
    if(Div1ImgCount == Div1ImgNotDisplayCount){
      $('.div2').hide();
    }
    .child1 {
      display: none
    }
    
    .child2 {
      display: block
    }
    
    .child3 {
      display: none
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="div1">
      <div class="child1">Some text</div>
      <div class="child2">Some text</div>
      <div class="child3"><img src="#" /></div>
    </div>
    
    <div class="div2">ABC</div>
    <!-- I want to hide .div2 -->
    Login or Signup to reply.
  3. You can use modern CSS selector :has(selector) for the job:

    .div1:not(:has(img)) ~ .div2 { display: none; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search