0

I want to know that why we use $(this) in jQuery. And what is $(this)?

var color = $(".selected").css("background-color");

$(".controls li").click(function () {
    $(this).siblings().removeClass("selected");
    $(this).addClass("selected");

    color = $(this).css("background-color");
});

In this code what "this" mean and what is the other option of using 'this'?

Tushar
  • 85,780
  • 21
  • 159
  • 179

4 Answers4

1

In javascript this inside a function represents the context in which the function invoked on, if a method is invoked without a context it will be the window object(or undefined in strict mode).

In jQuery event handlers this represents the dom element reference on which the handler is registered on so in your case this refers to the li element. in case of event delegation this will refer to the actual target of the handler like if an li was targeted by the handler($(document).on('click', 'li', function(){...})) then this will be the li element

Another option instead of using this will be the currentTarget property of the event object

$(".controls li").click(function (e) {
    // or $(e.currentTarget)
    $(this).siblings().removeClass("selected");
    $(this).addClass("selected");
    color = $(this).css("background-color");
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

$(this) is the current object.

In the above code - $(this) imeans - $(".controls li") (the li in .controls) from which the event triggered.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

$(this) is referred as current object. In your case you are triggering click action on <li> item in controls class selector. So this will be <li> in css class controls

Manish Shukla
  • 1,355
  • 2
  • 8
  • 21
0
$(this) 

is the object from which the event triggered or the current object the process is handling.

Venu
  • 184
  • 3
  • 14