Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}

1 Answers

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>
like image 96
Tushar Avatar answered Oct 27 '25 04:10

Tushar