Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "$(this)" and "this"?

I was reading the http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery. And got confused with use of this in these 2 code segments.

     $(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();
        });
     });
   });

When do we need $(this) and this? And what is the difference between them? Thanks in advance.

like image 883
gmail user Avatar asked Aug 29 '11 15:08

gmail user


People also ask

What does $( this refer to?

The findings are simple: 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 .

When we use $( this code?

Explanation: The $(this) selector is used to select current HTML elements. 19.

What is $( this in JavaScript?

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

When we should use $( this in jQuery?

this would refer to the current DOM element h1 which invoked the event. Enclosing it with a $ makes it a jquery object. So $(this) basically refers to the jquery h1 object . So $(this) = $('h1') where h1 is the event which triggered the event.


4 Answers

this refers to the DOM element itself; $(this) wraps the element up in a jQuery object.

In the first example, you need $(this) because .append() is a jQuery method.

In the second example, reset() is a JavaScript method, so no jQuery wrapper is needed.

like image 127
Blazemonger Avatar answered Oct 22 '22 07:10

Blazemonger


this by itself is just a regular object.

$(this) takes this and adds the jQuery wrapper so you can use the jQuery methods with the object.

like image 23
Justin Niessner Avatar answered Oct 22 '22 06:10

Justin Niessner


this refers to a DOM object. So reset() is a function of a form DOM object. append() on the other hand is a jQuery method so it has to be called by a jQuery object, hence the $(this).

When you surround this with $, you get a jQuery object back representing that DOM object.

like image 3
tskuzzy Avatar answered Oct 22 '22 07:10

tskuzzy


Generally in jQuery, this will be an instance of the DOM element in question, and $(this) builds a jQuery object around this which gives you the usual jQuery methods like each() and val().

like image 2
meagar Avatar answered Oct 22 '22 06:10

meagar