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

General Discussion

Using jquery .closest() instead of prev().

In order to help myself learn more I've been thinking of alternative ways of solving the problems. In looking at the jquery documentation it seems to me that .closest() could be substituted for .prev(). It doesn't work, but I don't understand why.

2 Answers

Hello again Jason,

It is fantastic that you are looking at new ways of solving problems. That's what you should do because that's innovative. Keep in mind that when looking at the jQuery documentation for different methods, pay close attention to the summary text for each method. With that in mind, closest() can all the way up the DOM tree to grab a reference to an element while prev() only selects a sibling element. Refer to the jQuery documentation when you have questions and all answers shall be revealed.

I've read the documentation for both a couple of times. Maybe I'm just not understanding something. I tried $(this).closest("span").show();. The way I'm reading the documentation this should work, but it doesn't.

It depends on how your document structure is set up. closest() is an ascendant selector so if you're trying to grab a sibling element, it's not going to work. If you're working on this in Workspaces, you can post a snapshot of your code and I can take a look at it. If not, you can post some of your HTML and JavaScript into a Codepen and I'll take a look at it that way.