2

i've been searching that why we use $(this) in jQuery . so i thought to ask it on stackOverFlow , i'm new to jQuery and i'm very curious to know about $this.

  <h1>Example Header</h1>

  <script>
    $('h1').on('click',function(){
      $(this).hide(); //???
    });
  </script>
Daniel
  • 1,438
  • 6
  • 20
  • 37

4 Answers4

2

Here this refers to the current DOM element on which we are working(on which event was called, say Click). Ex: in

$('h1').on('click',function(){

this would refer to the current DOM element h1 which invoked the event.

Enclosing it with a $ makes it a jquery object.

So $(this) basically refers to the jquery h1 object.

So $(this) = $('h1') where h1 is the event which triggered the event.

Nikhil Batra
  • 3,118
  • 14
  • 19
2
  1. The this keyword's value has nothing to do with the function itself, how the function is called determines the this value.
  2. It can be dynamic, based on how the function is called.
  3. You can change the this context through .call(), .apply() and .bind().

Understanding the “this” keyword in JavaScript

ozil
  • 6,930
  • 9
  • 33
  • 56
1

The value of this inside a click event is a DOM element (the one that was clicked).

Using $(this) converts it to a jQuery object. DOM elements do not have a hide() methods, but jQuery adds that and many other methods you can then call.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
1

"this" is a reference to the member that invokes the current function...

then you can wrap it in the jquery function $() to select it just like you would do for another selector. In the provided example this refers to h1