How to change the class of an element - Font Awesome

Asked

Viewed 750 times

3

I have an icon of Font Awesome on which I am trying to get the element to be clicked, change the icon of fa fa-plus for a fa fa-minus and when clicking again, the icon goes back to the fa fa-plus. How can I do that?

Here’s the code of what I’ve got so far:

$("#fa").click(function(){
    var linhaClicada = $(this);

    if (linhaClicada.removeClass("fa fa-plus")) {
        linhaClicada.addClass("fa fa-minus");
        //$("#excluir").hide();
    }
    else if(linhaClicada.removeClass("fa fa-minus")){
        linhaClicada.addClass("fa fa-plus");
    }
});

Note: I managed to get him to change the fa fa-plus to the fa fa-minus, but I’m not getting him back into the fa fa-plus when I click back.

1 answer

7


You can do it this way:

$('.minhaClass').click(function(){
    $(this).find('i').toggleClass('fa-minus fa-plus')
});
.minhaClass{cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css">

<span class="minhaClass"><i class="fa fa-minus"></i> Clica-me!</span>

  • 1

    The good thing about this code model is that you are not applying the click function directly to the element i. This way the click does not need to be exactly on the icon, but on the "context", that is, on the whole text (including the icon) that can/should perform the expected action. This improves the use of the element.

  • but here it is not going to always keep the same from a look at my code: '$('. badge pull-right'). click(Function(){ $(this). find('i'). toggleClass('fa-Minus fa-plus') });'

  • 1

    ignore my comment needed to put an id because with my class not caught now funfou obg friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.