1

I am using this code to remove and a CSS class:

$('.called').click(function() {
    $('called').removeClass('fa-phone-square').addClass('fa-check');
})

The problem is, it removes and adds classes to ALL tags with the class '.called'. I want this function to work only for the single item that has been clicked.

How would I do this?

Reza Saadati
  • 5,018
  • 4
  • 27
  • 64

3 Answers3

3

In jQuery event handlers this gets bound the the DOM node that fired the event.

$('.called').click(function() {
    $(this).removeClass('fa-phone-square').addClass('fa-check');
})
Oka
  • 23,367
  • 6
  • 42
  • 53
2

You would have to do this:

$('.called').click(function() {
    $(this).removeClass('fa-phone-square').addClass('fa-check');
})

"this" inside the click handler refers to the element that has been clicked and which you want to apply the changes.

If you instead apply the ".called" selector again it will select all items with the "called" class and apply the removeClass and addClass to all of them which is the behavior you are experiencing now.

Luis
  • 5,979
  • 2
  • 31
  • 51
  • @T.J.Crowder Yup, you have a point there, I guess it has become common practice (or maybe is just me) to call closures to anonymous functions in javascript. – Luis May 17 '15 at 14:54
  • :-) I have seen a few people do it. Which is unfortunate, because of course named functions are closures too. – T.J. Crowder May 17 '15 at 15:00
1

Inside the callback, $(this) refers to the element that was clicked.

You can also have the event as an argument in the callback and get the clicked element with event.target - https://api.jquery.com/event.target/

Difference between using $(this) and event.target - Difference between $(this) and event.target?

Community
  • 1
  • 1
manojlds
  • 290,304
  • 63
  • 469
  • 417