Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $(this) and this

I have the following code

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

This works just fine and sure enough the returned result is the url of a tag.

However if I change the above code to

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

The result is undefined.

Anyone please help to clear this out for me? I am banging my head for this ....

like image 411
Dylan Musch Avatar asked Sep 15 '10 23:09

Dylan Musch


2 Answers

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

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

like image 142
Stefan Kendall Avatar answered Oct 14 '22 13:10

Stefan Kendall


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

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

so .href is not an attribute of that jquery object, but it is of the dom object.

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

like image 32
brad Avatar answered Oct 14 '22 15:10

brad