Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alcibiades Montas
Alcibiades Montas
5,974 Points

When to use $(this) in Jquery?

Hi guys,

I went through the javascript deep dive and now in the JQuery one....sometimes i get confuse with the right usage of $(this). I know we are trying to pass information about a function/method that was previously used but wanted to know best usage...get a different definition!

2 Answers

Matt Campbell
Matt Campbell
9,767 Points

Basically, it refers back to the thing that you activated to run the bit of code you're looking at. So Christopher's example is good.

$(this) refers to the button you've clicked to run the function. Just makes life a bit easier rather than writing out the selector over and over. If in doubt, use the selector rather than $(this)

Christopher Hall
Christopher Hall
9,052 Points

In jQuery, $(this) is used to refer back to the parent object when you change scope, such as in an anonymous function like so:

$("#submitButton").on('click', function() {
    // within this anonymous function $(this) refers to the jQuery object $("#submitButton")
    // so you can use that as a source to traverse the DOM, add or remove objects, etc.
    $(this).addClass("submittingForm");
});