Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this) vs this in jQuery

Tags:

jquery

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();
     });
   });
 });
like image 659
penguru Avatar asked Aug 03 '10 19:08

penguru


People also ask

What is difference between $( this and this in jQuery?

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.

What is $( this used for in jQuery?

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 .

What is $( this in JS?

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

What is the meaning of $( this?

$(this) refers to the jQuery object created from current HTMLElement object.


2 Answers

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.

like image 175
Pointy Avatar answered Oct 05 '22 04:10

Pointy


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)

like image 26
spinon Avatar answered Oct 05 '22 06:10

spinon