skip to Main Content

I have several DIVs containing images generated from database.
However, there is a DIV doesn’t contain any image, but <img>. I need to hide this DIV, but somehow my jquery code doesn’t work!

Please take a look at my sample code and give me a hand.

Thanks!

$(function() {
$('.image-box').each(function() {
    if ( $(this).attr('src') == '') {
    $(this).hide();
  }
})
})
.image-box {
  border: 1px solid red;
  width: 180px;
  height: 130px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image-box">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div class="image-box">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div class="image-box">
<img>
</div>

2

Answers


  1. Check for the src attribute of any of the img elements in this:

    $(function() {
     $('.image-box').each(function() {
      if (!$("img",this).attr('src')) $(this).hide();
     })
    })
    .image-box {
      border: 1px solid red;
      width: 180px;
      height: 130px
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="image-box">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
    </div>
    <div class="image-box">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
    </div>
    <div class="image-box">
    <img>
    </div>
    Login or Signup to reply.
  2. You are getting the wrong element to get the src attr, you should get the children of the currently selected div. The below code works.

    $(function () {
      $(".image-box").each(function (index, item) {
    
        if (
          typeof $(this).children().attr("src") == "undefined" ||
          $(this).children().attr("src") == ""
        ) {
          $(this).hide();
        }
      });
    });
    .image-box {
      border: 1px solid red;
      width: 180px;
      height: 130px
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="image-box">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
    </div>
    <div class="image-box">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
    </div>
    <div class="image-box">
    <img>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search