Search code examples
jqueryclasstoggleparent

jQuery - toggle the class of a parent element?


I have a few list elements, like this:

<li class="item">
    <a class="toggle"><h4>ämne<small>2010-04-17 kl 12:54 by <u>nike1</u></small></h4></a>
    <div class="meddel">
        <span>
            <img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
            <a href="account.php?usr=47">nike1</a>
        </span>

        <p>text</p>
        <span style="clear: both; display: block;"></span>
    </div>
</li>

<li class="item odd">
    <a class="toggle"><h4>test<small>2010-04-17 kl 15:01 by <u>nike1</u></small></h4></a>
    <div class="meddel">
        <span>
            <img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
            <a href="account.php?usr=47">nike1</a>
        </span>

        <p>test meddelande :) [a]http://youtube.com[/a]</p>
        <span style="clear: both; display: block;"></span>
    </div>
</li>

And i'm trying to figure out how to make it so that when you click a link with the class .toggle, the parent element (the li element) will toggle the class .current.

I'm not sure if the following code is correct or not, but it's not working.

$(this).parent('.item').toggleClass('.current', addOrRemove);

Even if i remove "('.item')", it doesn't seem to make any difference.

So, any ideas?

Thanks in advance


Solution

  • toggleClass takes a class name, not a selector. Therefore, you shouldn't include a ..
    Change it to toggleClass('current') (without a .).

    Also, you can make your code more robust by calling closest instead of parent. The closest will search for the innermost parent element that matches the selector, so that it will keep working if the link is nested inside the .item.