Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,939 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