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

$('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.