[javascript] What's the difference between '$(this)' and 'this'?

I am currently working through this tutorial: Getting Started with jQuery

For the two examples below:

$("#orderedlist").find("li").each(function (i) {
    $(this).append(" BAM! " + i);
});
$("#reset").click(function () {
    $("form").each(function () {
        this.reset();
    });
});

Notice in the first example, we use $(this) to append some text inside of each li element. In the second example we use this directly when resetting the form.

$(this) seems to be used a lot more often than this.

My guess is in the first example, $() is converting each li element into a jQuery object which understands the append() function whereas in the second example reset() can be called directly on the form.

Basically we need $() for special jQuery-only functions.

Is this correct?

This question is related to javascript jquery this

The answer is


$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.


this is the element, $(this) is the jQuery object constructed with that element

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

thisMDN is contained in an execution context

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

execution contexts bind this

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

jQuery binds this

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.


Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.


Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.


this reference a javascript object and $(this) used to encapsulate with jQuery.

Example =>

// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')

// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)

// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()

//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()

//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value

or 

this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to this

this in equals method React: "this" is undefined inside a component function How to access the correct `this` inside a callback? jQuery $(this) keyword Difference between $(this) and event.target? 'this' vs $scope in AngularJS controllers Difference between getContext() , getApplicationContext() , getBaseContext() and "this" Use of "this" keyword in C++ What is context in _.each(list, iterator, [context])? What does 'var that = this;' mean in JavaScript?