What is the difference between $ (this) and this

I have the following code

$('a').click(function() { var url= this.href; alert(url); }); 

This works very well and the correct result is the tag url.

However, if I change the above code to

 $('a').click(function() { var url= $(this).href; alert(url); }); 

The result is undefined.

Can someone please help me sort it out? I hit my head about it ....

+6
javascript jquery this
source share
5 answers

$(this) creates a jQuery object that wraps this . A native DOM object has an href attribute, but jQuery does not.

$(this).attr("href") will work.

+19
source share

this in your case is the actual dom element, so the anchor tag

$(this) is a jquery object that wraps this dom element with all jquery properties.

therefore .href is not an attribute of this jquery object, but it has a dom object.

you can use $(this).attr('href') to achieve the same goal using the jQuery object.

+7
source share

This is because you are using javascript DOMElement in the first example and the jQuery object in the second example. The jQuery object wraps a DOMElement and provides you with many features.

You can access the url:

 $('a').click(function() { var url= $(this).attr('href'); alert(url); }); 
+2
source share

The difference between a DOM element and a jQuery selection.

"this" in the code you specified above is a link to a DOM element of a link. $ (this) creates a jQuery selection based on a DOM element that contains only this link.

Choosing jQuery will give you various features for little performance. Your link element has the href property (i.e. you can access it through this.href), while jQuery selection has all the usual jQuery properties and methods.

To get the link target this.href is definitely the way to go. It is simpler, faster, and less verbose.

0
source share

A lot of good answers, just wanted to add that you can do this too:

 $('a').click(function(e) { alert($(this)[0].href); }); 
0
source share

All Articles