Home > Mobile >  Hide a box if it doesn't contain an image
Hide a box if it doesn't contain an image

Time:12-24

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 >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img>
</div>

CodePudding user response:

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 >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img>
</div>

CodePudding user response:

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 >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s">
</div>
<div >
<img>
</div>

  • Related