views:

66

answers:

2

Hi, 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?

+8  A: 

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.

Pekka
Thanks for the explanation, so couldn't I get the jQuery object from the DOM object?
Vittorio Vittori
@Vittorio no, not without `$()`. The DOM object doesn't inherently contain the jQuery object. You have to use `$()` for jQuery to create the object first, based on the DOM object.
Pekka
thanks for help
Vittorio Vittori
+3  A: 

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

Sarfraz