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 Review

Xu Cheng
Xu Cheng
5,038 Points

prev() and next()

Hi I really not sure how to use prev() and next() even after reading the documentation. It is just confusing. Can someone explain this with some examples? Also i don't know how to deal with the quiz question $("p").prev().prev(), I don't know why it has to do it twice. Thanks in advance.

1 Answer

prev() and next() find the previous or next sibling of element they are called on. When you use prev() twice, you move further back the siblings by one element node. So not the one right next to the element the method was called on but the one before that. For example if you have an unordered list like this.

<ul>
<li id="first">first</li>
<li id="second">second</li>
<li id="third">third</li>
</ul>

and you would call prev() twice on the third li element like this

let first = $("#third").prev().prev().css("color", "blue");

it would turn the first li element blue.

next() just does the same but traverses forwards along the sibling elements.