user4831663
user4831663

Reputation:

How can I add class to parent if child contains class?

I am trying to add a class to a parent DIV if it has a child IMG element with class of "testing".

<article>
    <div id="on-1" class="box">
        <img src="110.jpg">
    </div>

    <div class="present">
        <img class="testing" src="image.jpg">
    </div>
</article>

I have set up if statement to check if class "testing" exists. I am having trouble adding class to the parent "article" element though.

if ($("article").find(".testing").length > 0) {
    $(.this.parentNode.parentNode).addClass("hasclass");
}

Upvotes: 4

Views: 9195

Answers (3)

Chris Kempen
Chris Kempen

Reputation: 9661

Based on your comment on @Tushar's answer, to help elaborate on traversing up many parent nodes, I usually take the following approach:

To add a class to the direct parent div:

$('article img.testing').parent().toggleClass('new-class', true);

And to add the class to the encompassing article parent:

$('article img.testing').parents('article:first').toggleClass('new-class', true);

I also like using toggleClass() as it seems 'cleaner' to avoid any chance of adding the same class twice to an element, although I'm sure jQuery would check for this.

Hope this helps!

Upvotes: 0

Tushar
Tushar

Reputation: 87233

Use parent() to select parent element.

$("article img.testing").parent().addClass('hasclass');

$("article img.testing").parent().addClass('hasclass');
.hasclass {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<article>
  <div id="on-1" class="box">
    <img src="110.jpg">
  </div>

  <div class="present">
    <img class="testing" src="image.jpg">
  </div>
</article>

Upvotes: 5

Ramanlfc
Ramanlfc

Reputation: 8354

$('div:has(img.testing)').addClass('hasclass');

Upvotes: 2

Related Questions