vitto
vitto

Reputation: 19496

jQuery: Differences between $(this) and this

I'm trying to understand what differences are between $(this) and this in jQuery, and eventually find a way to get $(this) object from this (this what??):

var last_btn;
$("#element").click (function () {
    if (last_btn != null && last_btn == this) {
        // to unselect the current button
        last_btn.removeClass ("selected"); // doesn't work because this is not $(this)
    } else {
        if (last_btn != null) last_btn.removeClass ("selected"); // to unselect another old button
        last_btn = this;
        $(this).addClass ("selected");
    }
});

As written in this post, I need to use this instead of $(this) object because it's the only way to assign a jQuery object to a var without loose his instance.

How can I do that?

Upvotes: 1

Views: 116

Answers (2)

Sarfraz
Sarfraz

Reputation: 382909

@Pekka is right and I find this post to be important to post here by Remy Sharp:

Upvotes: 3

Pekka
Pekka

Reputation: 449813

In the code you show, this is a reference to the pure DOM object with the ID element that got clicked.

$(this) will extend the DOM object into a jQuery object, which makes all the jQuery goodness like addClass available for it.

Upvotes: 10

Related Questions