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

Could $(this) be used instead of $('.spoiler button')? If so what are the pros and cons

Could $(this) be used instead of $('.spoiler button')? If so what are the pros and cons

3 Answers

Steven Parker
Steven Parker
229,732 Points

In that context, They should be interchangeable. And if you were to also use DOM traversal starting at "this" to show the span, then the same handler code could be used for more than one spoiler.

$('.spoiler button').click(function() {
  // Show the spoiler text
  $(this).prev().show();
  // Hide the "Reveal Spoiler" button
  $(this).hide();
}); 
Steven Parker
Steven Parker
229,732 Points

It depends on the context. If you're inside a method applied to that jQuery object, then you probably can use it as a substitute.

For a more specific answer, please show the code in with the question.

//Hide the spoiler text
$('.spoiler span').hide();
// When the button is pressed
$('.spoiler button').click(function() {
  // Show the spoiler text
  $('.spoiler span').show();
  // Hide the "Reveal Spoiler" button
  $(this).hide();
});

the video writes it like this:

//Hide the spoiler text
$('.spoiler span').hide();
// When the button is pressed
$('.spoiler button').click(function() {
  // Show the spoiler text
  $('.spoiler span').show();
  // Hide the "Reveal Spoiler" button
  $('.spoiler button').hide();
}); 

Would both be correct in this scenario? The only difference is that this selector only applies to the button being pressed and the other on to all the buttons if there where more, is this correct?