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 trialKevin Alvarez
4,851 PointsTraversing, i think
var captionText = $(this).children("img").attr("alt"); $caption.text(captionText);
I don't completely understand how this code works, especially this part $(this).children("img") So i'm pretty sure that "this" selects the element you clicked on and ".children" selects the previous or child elements of the one you clicked but then i'm lost with ("img") i don't know what is the purpose of this.
1 Answer
Erik Nuber
20,629 PointsYou have the correct idea
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
$(this) is the image that is clicked on. This is used as it is saying here is the item I clicked on and am working worth.
.children() is going to look at "this" as the parent element and will look for the children of this.
"img" is telling the .children() to search for the image tag.
In other words, we are looking for the image tag that is a child of "this".
finally, we add in the .attr("alt") which is going to look at that image tag and grab the attribute called "alt"
this will be passed into the captionText variable
.text() - sets just the text of $caption.
as a side note, you could add in .html() instead of .txt() if you wanted to set a specific html tag like "<p>" + captionText + "</p>". However when you use .html() it will replace all existing html within the area you are placing it. In this case, it would replace anything within $caption. Using just .txt() would replace just the text.