this vs. $(this)

Often in a function you’ll want to reference the object that called the function. For example, in a jQuery click handler function, you’ll want to easily access the DOM element that was clicked e.g.:

<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
<script>
$('li').click(function() {
// Add a class to the specific li that was clicked.
});
</script>

You can use Javascript’s this keyword which, in the case of an event handler callback, is a reference to the DOM element where the event began e.g.

<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
<script>
$('li').click(function() {
$(this).toggleClass('active');
});
</script>

That code will add the ‘active’ class to the specific li that was clicked.

But hang on, why are we using $(this) and not just this?

this vs. $(this)

When you instantiate jQuery, you do so like so: $( … ) where “…” is some parameter. You can pass in a string as the parameter e.g. $(‘li’). Or you can pass in a DOM node reference e.g.

// 'divs' is a collection of DOM node references
var divs = document.getElementById('div');
// $divs is a jQuery object referencing all the divs. Note the parameter is the variable 'divs', not a string
var $divs = $(divs);

So, if this is a DOM node reference, as it would be in many Javascript callback functions, you can wrap this in a jQuery object in order to get access to the jQuery method library.

Or, if you don’t care about using any jQuery method, you can of course just use pure JS e.g.

// Pure JS
this.classList.toggle('active');
// jQuery
$(this).toggleClass('active')

TL;DR: if this is a reference to a DOM element, the difference between this and $(this) is that the first is just the reference, the second adds the jQuery library to the reference.

Still got questions? We provide more demonstrations in the video below:


JS Dojo: Javascript Tutorials With Real-Time Help

Raise your skill to professional level in a live, interactive coding environment with an industry expert looking over your shoulder.

To learn more about JS Dojo and to join our private beta program, visit us here: https://getjsdojo.com

JS Dojo — Javascript Tutorials With Real-Time Help