Archetype
Archetype

Reputation: 45

Add class to parent based on image src attribute

I'm having a problem where a CMS is spitting out a grid of images based on a template, but if the project has less images than the grid it will spit out the blanks as well. So I want to add a class of to the parent element to hide the blanks based on the blank image src attribute. Here is what I have:

HTML

<div class="item">
  <a href="#">
     <img src="image-1.jpg">
  </a>
</div>
<div class="item"> <!-- Need to add class of 'hide' -->
  <a href="#">
     <img src=""> <!-- Blank Img -->
  </a>
</div>

jQuery

var image = $("div.item > a > img");
var srcs = image.attr('src');

$.each(image, function () {
   if(srcs.length == 0){
      $(this).closest('div').addClass("hide");
   }
});

Since I am a bit of a noob at this it's probably something simple. Thanks in advance for any help you can provide!

Upvotes: 2

Views: 3201

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206699

LIVE DEMO

$('img[src=""]').closest('.item').hide();

additionally instead of .hide() you can use .remove()

Upvotes: 0

Boynux
Boynux

Reputation: 6222

Simply use:

$('img[src=""]').parents ('div.item').hide()

Description: Selector find all img elements with empty source and parents method return paretns with given selector and finaly hide with actuallu hides div.item selector.

regarding to what @Felix suggests this is more efficeint:

$('img[src=""]').closest ('div.item').hide()

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817238

image.attr('src') will always return the src attribute value of the first selected element.

You want to test the attribute value of each element. You can use .filter [docs] to do this easily:

$('div.item > a > img').filter(function() {
    return $(this).attr('src').length === 0;
}).closest('div.item').addClass('hide');

Or use the attribute equals selector [docs]:

$('div.item > a > img[src=""]').closest('div.item').addClass('hide');

Upvotes: 0

P. R. Ribeiro
P. R. Ribeiro

Reputation: 3029

I modified your version of the code, so you can learn from it. You also will learn how to use the $.each().

 var image = $("div.item > a > img");

 $.each(image, function (idx, element) {
   if($(element).attr('src').length == 0){
      $(this).closest('div').addClass("hide");
       // remove
       $(this).closest('div').hide();
   }
});

You can play with it on fiddle

http://jsfiddle.net/r84NR/

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113517

Use .attr("src") will return the src attribute.

I would use each jQuery function for img.

$("img").each(function () {
    if($(this).attr("src") == "") {
         $(this).closest('div').addClass("hide").text("Hide class was added.");
    }
});

See demo here.

You can see the screen shoot bellow.

I used the following CSS style for .hide:

.hide {
    background: lightblue;
}

enter image description here

Upvotes: 0

Related Questions