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')) {

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


You could use:


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


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:


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