Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $(this) and this in jquery

Tags:

jquery

this

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 know what functions are available when I'm using it? (I know I can get them through firebug. but I would like to know if there any some other way- some doc may be)

like image 914
Sheldon Fernandes Avatar asked Sep 03 '10 05:09

Sheldon Fernandes


People also ask

What does $( this mean in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

What does $() return in jQuery?

$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.

How this works in jQuery?

The this is a simple javascript (DOM) object, $(this) will turn the object into a jQuery object. var myHeaderDiv = document. getElementById('header'); $myHeaderDiv = $(myheaderDiv); //just a variable transformed into jQuery object, as with this.

What is $() in jQuery library?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

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.

like image 111
Chris Jester-Young Avatar answered Sep 20 '22 23:09

Chris Jester-Young


$(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.

like image 35
Pranay Rana Avatar answered Sep 20 '22 23:09

Pranay Rana