What is the difference between $(this)
and this
in jQuery ? Here are two different usage :
$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).append( " BAM! " + i );
});
});
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
});
Difference between this and $(this)The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
this is a reference to the html DOM element that is the source of the event. $(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this .
$(this) is a jQuery object and this is a pure DOM Element object. See this example: $(".test"). click(function(){ alert($(this). text()); //and alert(this.
$(this) refers to the jQuery object created from current HTMLElement object.
The "this" variable refers (in such cases as the event handlers you've supplied) to a DOM element. Thus $(this) is a jQuery object containing just that one DOM element.
You should use plain "this" when the native DOM APIs suffice, and $(this) when you need the help of jQuery. Your second example is a good illustration; another might be when you just need the "id" or "name" of an element.
The difference is that this
by itself is a reference to the dom object that the event is acting upon. $(this)
is creating a jquery object from that dom object.
EDIT: So with the DOM object you aren't going to have access to all the jquery added functionality but only what the dom allows. Basically you can think of the this
by itself as the same as if you did document.getElementById(id)
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