I am looking to toggle the class of an icon which is inside of a link once the link is clicked. I have it working at the moment but when clicked all my icons change - I have more than one accordion on the page. I only want to change the icon of the link that is clicked. Can anyone help? I know it must be to do with 'this' but I can't figure it out.
jQuery code
$( ".accordion a" ).click(function() {
$( ".accordion a i" ).toggleClass('fa-caret-up ','fa-caret-down');
});
HTML code
<a href="#panel{accordion_number}">{accordion_heading} <i class="fa fa-caret-down linkIcon"></i></a>
You are not using the .toggleClass()
signature properly. The signature that you are trying to use on it is .toggleClass('class1 class2')
Try,
$( ".accordion a" ).click(function() {
$(this).find("i").toggleClass('fa-caret-up fa-caret-down');
});
And I missed to explain it, you need to use $(this)
inside the click event to target the currently clicked element. Otherwise it would affect all the elements matching the selector.