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
Check for the
src
attribute of any of theimg
elements inthis
: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.