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");
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With