577

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?

Zoe - Save the data dump
28.4k22 gold badges130 silver badges164 bronze badges
asked Jun 27, 2009 at 0:18
2
  • 2
    @Reigel, why was this protected? The OP questioned and guessed the correct answer. Commented Jul 24, 2013 at 4:45
  • 21
    @Reigel: I think I should ask this in meta, but if that's all that's required for protection, shouldn't all questions be protected Commented Jul 24, 2013 at 15:06

7 Answers 7

527

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

Liam
30k28 gold badges145 silver badges206 bronze badges
answered Jun 27, 2009 at 0:23
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a reason to use $(this)[0] over this if they're always the same?
@Jay If you prefer to type long than simply using 'this' then yes. $() 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".
@jay - There's no good reason to use $(this)[0] I was just using it to illustrate the concept. :) I do use $("#myDiv")[0] over document.getElementById("myDiv") though.
window.$(window) = $(window)
371

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

answered Sep 15, 2010 at 4:03

Comments

92

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.

answered Jun 27, 2009 at 0:24

Comments

76

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"); 
});
answered May 21, 2013 at 14:57

1 Comment

Note that change() is deprecated by now. Use .on("change", handler) instead.
47

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.

answered Feb 10, 2015 at 23:32

Comments

41

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

Flip
6,9098 gold badges54 silver badges84 bronze badges
answered Jun 27, 2009 at 0:23

Comments

-1

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')
Adam Buchanan Smith
9,4675 gold badges21 silver badges39 bronze badges
answered Nov 28, 2013 at 12:49

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.