Γ€mne2010-04-17 kl 12...">

JQuery - switch parent element class?

I have several list items, for example:

<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 the parent element (the li element) switch the .current class when clicking the link with the .toggle class.

I am not sure if the code is correct or not, but it does not work.

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

Even if I delete "('.item')", this does not seem to make any difference.

So any ideas?

Thanks in advance

+4
source share
1 answer

toggleClass accepts a class name, not a selector. Therefore, you should not include . .
Change it to toggleClass('current') (without . ).

In addition, you can make your code more reliable by calling closest instead of parent . closest will look for the innermost parent element that matches the selector so that it continues to work if the link is nested inside .item .

+7
source

Source: https://habr.com/ru/post/1307269/


All Articles