Anson Aştepta
Anson Aştepta

Reputation: 1143

Javascript : Check <img> is empty generate by for loop and if true do something

For instance we have something like below, which is generate brunch of img with different src :

//the for loop is not important but just giving you some idea

    for(i=0;i<100;i++){
      <img class="emptyPic result-image" src="{{picURL}}"/>
     }

and I'd like to check every img onload, if it's src is empty like <img src=""/>, i would like to do something, but in the example just make it display:none first. So i tried something like below with JQuery.

if($(this + ".result-image").attr('src')){
  ($(this + ".result-image").css("display","none")
}

i had put the if statmenet above into the for loop already and it should do the job but what is it not working?

Upvotes: 0

Views: 84

Answers (2)

Sangamesh Davey
Sangamesh Davey

Reputation: 75

If you want to check if img src is empty and want to do something...This may help;

HTML:

<!DOCTYPE html>
<html>
<body>
<img src="" class="image">

</body>
</html>

Javascript:

$(document).ready(function(){
   if($('.image').attr('src') == '') { 
      alert('got me'); 
    }
});

If you want to check if it is empty....This may help

HTML:

<!DOCTYPE html>
<html>
<body>
<img src="" class="image">

</body>
</html>

JAVASCRIPT:

if ($('.image').is(':empty')){
  alert("hi")
}

SOURCE:

How do I check if an HTML element is empty using jQuery?

Hope this helps

Upvotes: 1

sideroxylon
sideroxylon

Reputation: 4416

You can use pure CSS:

img[src = ''] {display:none;}

Upvotes: 2

Related Questions