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 Simple Lightbox Perform: Part 4

Jody Hsu
Jody Hsu
5,515 Points

Can I use $(this img).attr("alt") instead of $(this).children("img").attr("alt") ?

Since getting a child item can be written with $("#imageGallery a"), can we also use this same logic to get a child item when "this" is involved?

2 Answers

Hi Jody,

I agree with Ryan that it probably isn't possible. If that was possible it would be more equivalent to use the direct child combinator instead of a descendant selector since .children() only searches 1 level deep. i.e. $(this > img).attr("alt")

The jQuery constructor can take an optional 2nd argument which is the selector context. So instead of searching the entire document it would only search within the given context.

Your example could then be written like this:

$('img', this).attr("alt")

This is probably the closest you can get to what you tried to do. It's saying, "select all img elements within whatever element 'this' is referring to". this is the context to search within.

Again, to be closer to the project code, the direct child combinator should be used.

$('> img', this).attr("alt")

Selector context is implemented internally using .find() which is similar to .children() except it searches for all descendants. So even if you try to avoid using .children() or .find() in situations like this you'll still be using it behind the scenes.

To summarize:

// This
$('img', this).attr("alt")
// is implemented as
$(this).find('img').attr("alt")

// and this
$('> img', this).attr("alt")
// is implemented as
$(this).find('> img').attr("alt")
// which should be the same as
$(this).children('img').attr("alt")
Jody Hsu
Jody Hsu
5,515 Points

Hi, Jason

Thank you so much! Your answer is very detailed and easy to understand. :)

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

Hi, Jody. I don't believe this is possible. I did a few quick tests Codepen to confirm, and none of them worked. If someone else knows better, they can chime in, though.

Jody Hsu
Jody Hsu
5,515 Points

Hi, Ryan.

I see. Thank you :)