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

.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>');

$('body').append($overlay);
$overlay.append($img);
$overlay.append($caption);

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

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


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



$($overlay).click(function(){
    $overlay.hide()
});

Specifically this portion of the code using the children method

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

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>
</div>