开发者

Apply class if empty

开发者 https://www.devze.com 2023-03-30 14:04 出处:网络
I need to check whether an img src is empty and then apply a class to another element. Here is the HTML

I need to check whether an img src is empty and then apply a class to another element.

Here is the HTML

<span class="page-icon"><img src="" width="40" height="40" alt="P开发者_如何转开发rivacy" /></span>

If the img src is empty, apply the class hide to the span.page-icon.


$('img[src=""]').parent().addClass('hide')


Use an attribute selector to get img elements with an empty src attribute.

$("img[src='']").parent().addClass("hide");


Something like this should do it for all images on a page...

$('img').each(function(){
 var src = $(this).attr('src');
 if (!src){
  $(this).parent('.page-icon').addClass('hide');
 }
});


$('span.page-icon img').each(function() {
    console.log(this.src);
    if (this.src.length <= 0) {
        $(this).parent().addClass('hide');
    }
    else if ($(this).attr('src').length <= 0) {
        $(this).parent().addClass('hide');
    }
});

Fiddle: http://jsfiddle.net/maniator/kk9MQ/


$("img").each(function()
{

   if($(this).attr("src") === "")
   {

       $(this).parent().addClass("hide");

   }

});


$('span').has('img[src=""]').addClass('hide');

Look for any span that has an img with src="" and add the class hide


If the span will only contain a single image tag this will work:

$('span.page-icon:has(img[src=""])').addClass('hide');

http://jsfiddle.net/Dhfam/


This should work:

if ($(".page-icon img").attr("src").length == 0) {
  $(".page-icon").addClass("hide");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号