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

$('button') on removeClass but not $(this)?

Maybe I missed it but why is $('button').removeClass('selected') used instead of $(this).removeClass('selected')?

$(document).ready(function () {
    $('button').click(function () {
        $('button').removeClass("selected");
        $(this).addClass("selected");
    }); // end button.click
}); // end ready

1 Answer

Paolo Scamardella
Paolo Scamardella
24,828 Points

Because, in this case, if you just use $(this).removeClass("selected") instead of $('button').removeClass("selected"), then all your buttons will be "selected". If you keep clicking on all your buttons, then all buttons will be highlighted. The reason David is using $('button').removeClass("selected") first is because he wants to make sure it will remove all selected class to all buttons (including the one that is being clicked) and then reapply the selected class to only the one that is being clicked. Doing so, the other buttons will not be highlighted while clicking on the current button. Hope that makes sense. If not, I will try to explain it better.

Remember, $('button') means to all buttons on your screen and not just a single button. Using $(this) inside $('button').click refers to the button that is being clicked.

Thank you that does make sense.