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!

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


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>");




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

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



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

Michael Hulet
Michael Hulet
47,909 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:


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.