2

So, this is my code

     $(".heart.fa").click(function() {
          $(this).toggleClass("fa-heart fa-heart-o");

//Wanna check here is its fa-heart or fa-heart-o

           var row = $(this).closest("i");
           var rowId = row.attr("id");
            alert(rowId);

        });

<div>
  <i id= '".$i."' class='heart fa fa-heart-o'></i>
</div>

Want to check inside this function if it's currently fa-heart-o or fa-heart

MrRobot9
  • 2,402
  • 4
  • 31
  • 68

3 Answers3

2

The hasClass function is probably what you want https://api.jquery.com/hasclass/

So you would do something like:

if($(this).hasClass('fa-heart-o')){
//logic for having fa-heart-o
}
else{
//logic for having fa-heart
}
David
  • 377
  • 5
  • 14
1

Try this-

$(this).toggleClass("fa-heart fa-heart-o");

if($(this).hasClass('fa-heart') && !$(this).hasClass('fa-heart-o')){
  console.log('class is fa-heart');
} else if($(this).hasClass('fa-heart-o') && !$(this).hasClass('fa-heart')){
  console.log('class is fa-heart-o');
}
soccer7
  • 3,547
  • 3
  • 29
  • 50
1

Shorter syntax with ternary operator and one major change:

$(".heart.fa").click(function(e) {
    $(e.target).toggleClass("fa-heart fa-heart-o");

    $(e.target).hasClass("fa-heart-o") ? console.log("It was fa-heart-o") : console.log("It was fa-heart");
});

I am using e.target instead of this. Better safe than sorry. You can read about the differences here.

nemanja
  • 664
  • 5
  • 16