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

Is .prev().prev() valid code?

Hi everyone,

In a Quiz Question in the second chapter of jQuery Basics, Andrew gives a code example of

$('p').prev().prev().remove();

I understood the question and got it right, but I'm curious to know whether you can use double instances of .prev()/.next()/etc to target elements. Or was he giving an example of invalid code?

For example, in this HTML:

<h1>H1 text</h1>
<h2>H2 text</h2>
<p>P text</h1>

could I use this jQuery:

$('p').prev().prev().something();

to target the h1?

Cheers,

Ede

1 Answer

Steven Parker
Steven Parker
231,122 Points

:point_right: Yes, you can stack these things, as deep as you want as long as it is appropriate for your DOM. I've done this in production code on more than one occasion.

Hi Steven,

Good to know. Cheers for the answer.

All the best,

Ede