简体   繁体   中英

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

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> 

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM