简体   繁体   中英

Change element class with jQuery

I'm not certain why this won't work, maybe someone can help. I got this code:

<dd class="accordion-navigation">
  <a href="#panel3" class="switch"><i class="plus"></i> Title</a>
  <div id="panel3" class="content">
    ...
  </div>
</dd>

When I click on the <a> I'd like the class of the i-element switch from 'plus' to 'minus'. This is the code I have so far:

$('dd.accordion-navigation').on('click', 'a.switch' function(){
  $(this).find(i).removeClass('plus').addClass('minus');
});

Unfurtunatly it does not work. I would be really happy, if I could get a hint.

Thanks in advance Florian

Change the selector from a variable to a selector.

$(this).find('i').removeClass('plus').addClass('minus');

This would work.

In the code above, you were having i which in this context would have been a variable. But you don't have any variables, to get the data or value from. So, you need to be passing a String to detect the HTML element. 'i' in this case would be valid. Otherwise you can create a seperate variable, with the value of string i element. Like this

var i = 'i';

...and then you can use it. Otherwise, you'll have to stick to the conventions.

Unless you have a variable i = "i"; , that won't find anything.

$('dd.accordion-navigation').on('click', 'a.switch' function(){
  $(this).find('i').removeClass('plus').addClass('minus');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM