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

CSS jQuery Basics (2014) Creating a Password Confirmation Form Perform: Part 1

why to use methods like next() and prev() if you can do $(span)

why to use methods like next() and prev() if you can do $(span)

1 Answer

Sometimes you don't know a specific element's id or class value (or even what element it is) but you still might want to grab that element. next() and previous() help tremendously with this — all you have to know is the target element's siblings.

For example, say you're creating a ToDo list of sorts — (you're generating li elements on the fly, or maybe building whole ul elements dynamically):

<h1>My List</h1>
<ul>
    <li>Task One</li>
    <li>Task Two</li>
    <li>Task Three</li>
    <li>Task Four</li>
    <li>Task Five</li>
</ul>

In this case, you could grab the first ul by $('h1').next(); without having to assign it any arbitrary ids or classes. You could do something similar with the lis.

So as you see, those jQuery methods aren't so much competing with each other as working in concert to make DOM manipulation easier (and more cross-browser capable) than straight javascript.

Good luck!