Skip to content Skip to sidebar Skip to footer

Jquery Toggle Class On Closest Span

I am trying to replace a class with another class when a panel heading is clicked like so: This currently isn't working (toggling the class) - any ideas? jQuery: $('.panel-head

Solution 1:

According to jQuery docs, we use closest to find element which is outer/upper to the element.

http://api.jquery.com/closest/

"For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree."

So in your case the span is inside the clicked element so you need to use find instead of closest.

Try this. http://jsfiddle.net/aamir/4RCMc/1/

 $('.panel-heading').click(function () {
     var$span = $(this).find('span.fa');
     if ($span.hasClass('fa-caret-down')) {
         $span.removeClass('fa-caret-down').addClass('fa-caret-right');
     } else {
         $span.removeClass('fa-caret-right').addClass('fa-caret-down');
     }
 });

Or try http://jsfiddle.net/aamir/4RCMc/3/

 $('.panel-heading').click(function () {
     $(this).find('span.fa').toggleClass( 'fa-caret-down', 'fa-caret-right' );
 });

Read more here: https://coderwall.com/p/wxjljq

Post a Comment for "Jquery Toggle Class On Closest Span"