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

At the beginning of stage 2, section 9 of 10, jQuery Basics: why are both spoilers shown, but only one removed?

$(".spoiler button").click(function() { $(".spoiler span").show(); $(this).remove(); });

If the second line of the above code targets both spans under the .spoiler class, then why doesn't the third line remove both buttons under the .spoiler class?

1 Answer

That's because $(this) is relative to the event handler. In this code, the anonymous function is called when a button is clicked. There can be many instances of buttons with the class 'spoiler', but $(this) ONLY refers to the one that was clicked.

If instead, you had written this:

$(".spoiler button").remove();

Then both of the buttons would be removed.

Thanks! Your explanation clarified this code's behavior nicely.