StephenMeehan
StephenMeehan

Reputation: 1113

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?

Upvotes: 1

Views: 73

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240878

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.

Upvotes: 5

Kobi
Kobi

Reputation: 138007

You can use the :has selector:

$('figure:has(img.right)').addClass('test');

Upvotes: 3

Related Questions