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.

JavaScript

nicholas maddren
nicholas maddren
12,793 Points

How does jQuery know to put the caption inside of the <p> tag?

Hey guys being following jQuery basics and I'm just wondering how jQuery knows how to put the captions in-between the <p> tags?

Here is the code:

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

$overlay.append($image);

$overlay.append($caption);

$("body").append($overlay);

$("#imageGallery a").click(function(event){
  event.preventDefault();
  var href = $(this).attr("href");
  $image.attr("src", href);
  $overlay.show();


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

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

});

I'm just very curious to how it does this?

Michael Hulet
Michael Hulet
47,842 Points

I often wonder the same thing myself, but I just wanted to warn you of a little syntax error near the top. You forgot to add the > to the closing </div> tag stored in var $overlay. It should look like this:

var $overlay = $('<div id="overlay"></div>');

1 Answer

$caption, at that point, is just a DOM element like anything else you would have in your HTML. If your HTML looked like this:

<body>
    <div></div>
</body>

you could use jQuery to add text to you div like so:

$('div').text("new text here");

you are doing the same thing in your example, the only difference is you aren't adding the caption <p> directly into the HTML file, instead you are inserting it into the DOM with jQuery and then modifying the text.