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 jQuery Basics (2014) Creating a Spoiler Revealer Perfect

Farid Wilhelm Zimmermann
Farid Wilhelm Zimmermann
16,753 Points

Andrew used .append(), to add the two buttons to the end of the .spoiler element. Why does .prev select the FIRST span?

Well, Andrew used the .append() method to add our two reveal buttons to the end of the paragraph with the class spoiler. He uses $('button').prev/$(this).prev to select the both of the span elements and to reveal them again.

But if .append() adds our to buttons to the END of the .spoiler element, wouldnt $('button').prev select the last .spoiler span and the first button element? (As it seems to select the previous element?).

Am a bit confused with this. Thanks for your help already guys!

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I see where you're getting confused, and I get it. But when we are talking about the .prev method we're talking about the previous element in the DOM. So if I had three paragraphs in a row, and I currently have the third paragraph selected then the .prev will target the second paragraph:

<p>First paragraph</p>
<p>Second paragraph</p>  // .prev() will target this one
<p>Third paragraph</p>  //if this one is currently selected

So when he selects that button (whichever button it is) it's going to select the first sibling closest and upwards in the DOM. In this case, a span.

edited for additional clarification

Remember, that each of these spans are inside their own paragraph parent container. So we're targeting each span and then adding the button after the span. So the order would actually look a bit like this in HTML:

<p>
   <span></span>
   <button></button>
</p>

<p>
   <span></span>
   <button></button>
</p>

This means that the previous sibling to each button will be the span that is a sibling to the button that is clicked.

Hope that helps! :sparkles:

Thank you Farid and Jennifer!