Reputation: 89
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
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