Arturas Strazdas Arturas Strazdas - 7 months ago 90
Javascript Question

Hide image if src is empty

I'm trying to hide

<img>
if the source is empty. But I have no luck.

I found few posts here, but it doesn't work for me.

Here is my code, it's table based because it will be a template:
Images:

<td width="92%" align="center" class="imagenes_desc">
<a href="#" class="showcase"><img class="imagen" src="http://webs.ono.com/norfolk/ebay/images/01.jpg" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
</td>


Here is the Javascript I'm trying to implement.

<script type="text/javascript">
$(document).ready(function(){
if ($(".imagen").attr(src="") == "") {
$(".imagen").hide();
}
else {
$(".imagen").show();
}
</script>


I'm not very familiar with JS, I found this script here on Stackoverflow, but I can't get it to work.

Update

Trying this, but doesn't work (Chrome hides well, but Firefox and IE don't):

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type="text/javascript">
$("imagen").each(function(){

if ($(this).attr("src") == "")
$(this).hide();
else

$(this).show();
});
</script>
<style>
.hide {display:none !important;}
.show {display:block !important;}
</style>


Thanks,

Answer

How about using jQuery's attribute selectors?

    $(document).ready(function(){
        $('.imagen[src=""]').hide();
        $('.imagen:not([src=""])').show();
    });

Working example here