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 AJAX Basics (retiring) AJAX and APIs Adding jQuery

Giovanni Dalla Rizza
Giovanni Dalla Rizza
10,637 Points

using of 'this' to removeClass button

Can't understand why I can't use 'this' for add and removing class at the same time.

This code works:

$('button').click(function() {
  $('button').removeClass('selected');
 $(this).addClass('selected');  
 });

This doesn't work:

$('button').click(function() {
  $(this).removeClass('selected');
 $(this).addClass('selected');  
 });

2 Answers

Hi Giovanni,

At any given time, one of the buttons has the "selected" class applied to it. We don't want 2 buttons having the "selected" class.

So when you click on a button, either that button or one of the other buttons has the selected class.

The working code is saying, select all of the buttons and remove the "selected" class. Then add it to the one that was just clicked on. This insures that the button you just clicked on is the only one that has the "selected" class.

The non-working code is saying, remove the "selected" class from the button that was clicked and then add it back in. This doesn't really do anything. You're removing a class and then putting it back on the same element.

If one of the other buttons had the "selected" class then you're going to have 2 buttons now with the selected class.

Let me know if it's still unclear.

lesak
lesak
6,260 Points

This really helped me. Thanks!

Routine Poutine
Routine Poutine
26,050 Points

Quite helpful, as I'm still trying to grok 'this.'