tags:

views:

117

answers:

6

What is the fundamental difference between using $(this) vs this

$('.viewComments').click(function(ev){
    //returns the desired value
    alert(this.getAttribute('id'));

    //Gives an error sayin function is not defined 
    alert($(this).getAttribute('id'));

    //returns the desired value
    alert($(this).attr('id'));
});

What i thought was "$(this)" will contain all functions that "this" has and more..But that doesn't seem to be the case.

So what exactly is $(this)? and

Hw do i knw what functions are avaliable when im using it? (i knw i can get them through firebug. but i would like to know if there any some other way- some doc may be)

A: 

$(this) is the current object that was selected using a jQuery selector or event attached to the object.

so if you have $('#myelement').click(..... then $(this) referes to the element that was clicked on so that $(this).hide() hides that element.

griegs
+1  A: 

$(this) - represent current DOM element on which event this function is called

The this keyword - In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

Pranay Rana
It helps to note that `$(this)` represents the DOM element wrapped as a jQuery object *because* and *when* `this` refers to the DOM element as a native DOM API object
Shrikant Sharat
+13  A: 

this is the DOM object, whereas $(this) is the jQuery wrapper around same.

When using this, you can call DOM methods on it, but not jQuery methods. When using $(this), you can call jQuery methods on it, but not DOM methods.

Chris Jester-Young
Very clear and concise, excellent answer.
Ender
+1 for correctness and conciseness
Darko Z
So is it more advantageous or a best-practice to use $(this) over this in my jquery code?
Sheldon Ferns.
@Sheldon: Of course. You want to be able to use all the juicy jQuery goodness, don't you? :-)
Chris Jester-Young
you bet i do! :) thanks
Sheldon Ferns.
A: 

in jQuery the $() notation is a shorthand for the jQuery selector, so if you say $(this) you are asking jQuery to re-select your object. Then you have the usual jQuery functions available. "this" is the object selected by the outer jQuery call.

Marco
+1  A: 

Here are two articles that you may find helpful:

What is this? by Mike Alsup

jQuery's this: demystified by Remy Sharp

Alek Davis
A: 

in jQuery, this refers to the DOM object, and $(this) refers to the same object but with jQuery methods added

you can't call this.each() because each is not a DOM method, its a jquery method

you can call $(this).each() because $(this) returns a jquery object

each