You could use addClass function parameter too, some find it less readable though:
$('.expositie').find('.right img').addClass(function(){
return $(this).closest(".expositie").height() > $(this).height() ? "toggle" : "";
});
Question
I'm trying to add a class to an image if the height of the image is smaller than the height of the containing div. However, jQuery adds the class to all images if one image is smaller than the containing box. How do I get the jquery to only add the class to the images that are smaller than the containing divs?
I have experience with jQuery whatsoever. This is the first code I ever wrote in jQuery.
$('.expositie, .right img').each(function(){
if ($(".expositie").height() > $(".right img").height()) {
$(".right img").addClass("toggle");
}
});
Solution
You could use addClass function parameter too, some find it less readable though:
$('.expositie').find('.right img').addClass(function(){
return $(this).closest(".expositie").height() > $(this).height() ? "toggle" : "";
});
OTHER TIPS
Like this :
$('.expositie, .right img').each(function(){
if ($(this).closest(".expositie").height() > $(this).height()) {
$(this).addClass("toggle");
}
});
closest
lets you find the first enclosing element verifying a given selector.
You could also use filter
which I find clearer:
$('.expositie, .right img').filter(function(){
return $(this).height()<$(this).closest(".expositie").height()
}).addClass("toggle");
EDIT : I have a doubt about your intent. Should there be a comma in the first selector ?