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
Andrew Smith
14,330 PointsAt 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
Jose Soto
23,407 PointsThat'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.
Andrew Smith
14,330 PointsAndrew Smith
14,330 PointsThanks! Your explanation clarified this code's behavior nicely.