Add a class to a figure only if a image within figure has a class

How would I add a class to a figure element if an image inside it has a class of right?, I only want this to execute if a image has a class of right.

$(function() {
  if ($('img').hasClass('right')) {
    $('figure').addClass('test');
  }
});

This adds a class test to every figure on the page?


solution

You could use:

$('img.right').closest('figure').addClass('test');

If the figure element is always the immediate parent element you could also use:

$('img.right').parent('figure').addClass('test');

As a side note, the reason your example wasn’t working was because you were adding the class test to all figure elements when you used $('figure').addClass('test').

You needed to get the context of the element, which would look more like this:

$('img.right').each(function(){
  $(this).parent('figure').addClass('test');
});

Avoid the .each() loop and use one of the other suggestions, though.