Steeff
Steeff

Reputation: 25

Jquery toggleclass won't work

My toggleclass function won't work, and I have no clue why. Any help is appreciated thanks!

jsfiddle: http://jsfiddle.net/t763P/1460/

<li id="toggle-favicon">
    <a href="#">Orders <span class="fas fa-chevron-left"></span></a>
    <ul class="nav nav-second-level">
        <li>
            <a href="#">File orders</a>
        </li>
        <li>
            <a href="#">Product orders</a>
        </li>
    </ul>
</li>

$('#toggle-favicon').click(function(){
    $(this).find('span').toggleClass('fa-chevron-left fa-chevron-down');
    console.log($(this).find('span'));
});

Upvotes: 1

Views: 91

Answers (1)

void
void

Reputation: 36703

In latest version of font awesome, <span class="fas fa-chevron-left"></span> will get converted to some SVG Element. And the corresponding span element is removed.

Hence, to change the class of the icon, you will need to toggle the class of this svg element.

Also keep in mind that .toggleClass wont work on svg elements as jQuery v1.x can not do that. So you will need to use .attr("class" ... ) method.

$('#toggle-favicon').click(function() {
  var $el = $(this).find('svg');
  $el.attr("class", function() {
    return $(this).attr("class").indexOf("fa-chevron-left") != -1 ? "fa-chevron-right" : "fa-chevron-left";
  })
});

Fiddle

If you use jQuery 3.x then you can use .toggleClass as well...

$('#toggle-favicon').click(function() {
  var $el = $(this).find('svg');
  $el.toggleClass("fa-chevron-left fa-chevron-right");
});

Fiddle

Upvotes: 3

Related Questions