user2395853
user2395853

Reputation: 89

How to toggle class in conditionally for a specific element?

I need to toggle a class of an element only if its grandparent element has a specific class. The code is like this:

<ul>
    <li class="active">
        <a class"something" href="#"><span class="icon-a"></span></a> 
    </li>
    <li>
        <a class"something" href="#"><span class="icon-a"></span></a>
    </li>
    <li>
        <a class"something" href="#"><span class="icon-a"></span></a>
    </li>
</ul>

And the jQuery code I have tried is:

if ($(".something span").parents('li').hasClass("active") && $(".something span").hasClass("icon-a")) {
$(".something span").toggleClass("icon-a").toggleClass("icon-b");
}

The problem is all the span elements got its class toggled. I only need to toggle if the grandparent element <li> has an "active" class.

Upvotes: 1

Views: 485

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

Just select the elements you mean, and forget about the conditional.

$('li.category.active > a.something > span.icon-a').addClass('icon-b');

Upvotes: 1

Related Questions