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 jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 4

Strange Behaviour - jQuery

First, we gave the variable "Caption" the following content:

var $caption = $("<p></p>");

However, in jQuery (inside the linked javascript file), when we later change its text to the value of the alt attribute of the image by adding the following code:

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

//the keyword 'this' refers to a link (anchor element) which links to the image and is its parent element by the way

it shows in the browser as:

   <p>The Caption</p>

Why wasn't it displayed as:

    The Caption

In other words, how does the browser automatically tell that the previous value of the variable $caption were tags (they were <p></p>) which it inserted the text into?

I'm not sure if this is what you're asking. $caption becomes <p></p> when we save it as $("<p></p>"); When the browser sees <p></p> it is displayed as if you put <p></p> right into the html. You wouldn't see the tags, just the content. How does the browser do that? Personally I think it's magic.

1 Answer


var $caption = $("<p></p>")

in jQuery is equivalent to writing

var caption = document.createElement('p')

in JavaScript.

When the JavaScript file is loaded the browser reads this code and converts it into a DOM element, which is why you see the '<p></p>' with the text inside when you use the inspector.

Thank you!! I've been waiting for an answer lol ?