bikey77gy
bikey77gy

Reputation: 41

jQuery: add class to parent element when child has class

I'm trying to add class '.open' to the parent li for the children with class .showme I've tried several things so far (prev, prevAll, has etc) but I can't get it right.

This is my html structure and also a jsFiddle to work on. Any suggestions will be appreciated.

<ul class="product-categories">
    <li class="sub">
        <a href="#">Women</a>
        <ul>
            <li class=""> <a href="#">Clothing</a></li>
            <li class="showme"> <a href="#">Footwear</a></li>
        </ul>
    </li>
    <li class="no-sub"> <a href="#">Men</a></li>
    <li class="no-sub"> <a href="#">Children</a></li>
    <li class="offers"> <a href="#">Offers</a></li>
</ul>

$(".showme").prevAll("li.sub:first").addClass("open")

Upvotes: 0

Views: 7050

Answers (4)

Adil
Adil

Reputation: 148110

You need to use closest() instead of prev() as prev and prevAll() will look the previous siblings and you need to search the parent. You probably do not need :first in selector as cloest will return you single element.

Live Demo

$(".showme").closest("li.sub").addClass("open")

As an additional note, you did not include required js library on given fiddle.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Use .closest(), Find the first element with class .showme then find the closest parent li with class sub

$('.showme:first').closest('li.sub').addClass('open');

Upvotes: 2

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

How about this?

$('.showme').closest('li.sub').addClass('open');

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

$(".showme").closest("li.sub:first").addClass("open");

see reference closest

Upvotes: 0

Related Questions