raklos
raklos

Reputation: 28545

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-heading').click(function () {
            if ($(this).closest('span.fa').hasClass('fa-caret-down')) {
                $(this).closest('span.fa').removeClass('fa-caret-down').addClass('fa-caret-right');
            }
            else {
                $(this).closest('span.fa').removeClass('fa-caret-right').addClass('fa-caret-down');
            }

        });

HTML:

  <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseOne">
     <h4 class="panel-title">
         Main <span class="fa fa-caret-down fa-lg pull-right"></span>
     </h4>
  </div>

Upvotes: 0

Views: 882

Answers (1)

Aamir Afridi
Aamir Afridi

Reputation: 6411

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

Upvotes: 5

Related Questions