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)
$(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.
$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.
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.
$() = 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.
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.
$(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With