JavaScript and the DOM


In the last exercise, we were toggling every 'Recent Projects' button instead of only the one we clicked on.

We can select the specific element we clicked on with the jQuery selector $(this).

The syntax looks like this:

$('.example-class').on('click', function() {
  1. $(this) selects the clicked element. If there are multiple elements with a class of .example-class, this will only toggle the class of the one that is clicked on.
  2. Notice that $(this) does not require quotes around it, since it is not a CSS class. Instead, this is a JavaScript keyword.
  3. $(this) behaves just like our other selectors. We can attach toggleClass or toggle to it in the same way.
Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.