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 trialedeharrison
Full Stack JavaScript Techdegree Student 11,127 PointsIs .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
231,269 PointsYes, 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.
edeharrison
Full Stack JavaScript Techdegree Student 11,127 Pointsedeharrison
Full Stack JavaScript Techdegree Student 11,127 PointsHi Steven,
Good to know. Cheers for the answer.
All the best,
Ede