Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


.children() Method and Traversing the DOM

This is a question from one of the JQuery projects here on treehouse, building the light box. The program works fine, the issue is specifically the .children() method and traversing the DOM. Have some questions on how it works.

You can view the live site I created for the project here http://cssdojo.net/lightbox/

var $overlay = $('<div class="overlay"></div>');
var $img = $('<img></img>');
var $caption =$('<p></p>');


$('#imageGallery a').click(function(event){
    var $capture = $(this).attr('href');

    $img.attr('src', $capture);

    var captionText = $(this).children('img').attr('alt');


Specifically this portion of the code using the children method

    var captionText = $(this).children('img').attr('alt');

When I view the live site, the p tag created by the $caption variable looks like its a sibling of the appended img tag, not its child as shown in the image below. Notice how they are both indented the same amount, usually a child is one indent under the parent.

alt text

1 Answer

Keep in mind that "this" in that specific code refers to the imageGallery unordered list and the children it's selecting for are all of its children image elements. Down below, the "p" tag can only be a sibling of the "img" element, both of which are children of the div with the .overlay class.

So this code...

var captionText = $(this).children('img').attr('alt');

...has nothing to do with these elements below...

<div class="overlay" style="display: block;">
  <img src="images/library.png">
  <p>Library by Tyson Rosage</p>