Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AJAX Basics (retiring) AJAX and APIs Adding jQuery

Giovanni Dalla Rizza
Giovanni Dalla Rizza
10,633 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,038 Points

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