0

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

4 Answers 4

2

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');
Sign up to request clarification or add additional context in comments.

1 Comment

+1 to this for also including :first so that the search stops at first element found instead of searching the entire DOM.
0
$(".showme").closest("li.sub:first").addClass("open");

see reference closest

1 Comment

:first is superfluous since .closest() already selects only the first matching element.
0

How about this?

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.