Somebody
Somebody

Reputation: 9645

$(this) and this, what difference?

Could someone please explain a bit, what difference between them?

For example I could do that with "that":

var bar;
button.click(function () {
    if (bar == this) {
        alert('same');
    }
    bar = this;
});

and couldn't with $(that):

var bar;
button.click(function(){
  if(bar == $(this)) {alert('same');}
  bar = $(this);
});

Upvotes: 3

Views: 230

Answers (4)

kgiannakakis
kgiannakakis

Reputation: 104196

this is the plain Javascript object.

$(this) is a jQuery wrapped element. You are allowed to call jQuery methods with it.

Upvotes: 7

David Hellsing
David Hellsing

Reputation: 108530

Your second example doesnt work, because every time you use the $(this) function, it returns an unique jQuery Object:

var a = document.createElement('a');
var b = $(a);
var c = $(a);

Now, b and c are both unique jQuery instances.

console.log(c == b) // prints false

When using jQuery click events, this is the event.currentTarget in the callback, which is the HTML element that bound the click:

button.click(function(e) {
    console.log (e.currentTarget == this) // prints true
})

$(this) or jQuery(this) is a function that returns the HTML element wrapped in a unique jQuery Object, and contains all jQuery prototypes.

Upvotes: 7

Blair McMillan
Blair McMillan

Reputation: 5349

Here's quite a good page that explains it in detail with examples.

(Note: It was also the first google result for "jquery this")

Upvotes: 1

strager
strager

Reputation: 90062

$(this) creates a jQuery object containing this. this is the HTMLElement representing the button which was clicked.

Upvotes: 1

Related Questions