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

Ashton Holgate
Ashton Holgate
6,021 Points

Why does .text() add the variable captionText inbetween the <p></p> brackets?

var $caption = $("<p></p>"); is created, $caption.text("Example"); is called, and what we seem to end up with is <p>Example</p>

Why does the text entered appear between the <p> tags? In the jQuery documentation it does not appear that positioning the text between tags is a feature of .text() so why is it happening?

It clearly is a feature of the tags, I'm a bit confused as to how I would be supposed to know.

I am sure I'm missing something. All help is greatly appreciated :)

1 Answer

andren
andren
28,558 Points

<p> is the starting tag of the p element, </p> is the ending tag. Anything placed inside the element (in other words between the tags) is referred to as the content of the element.

The jQuery documentation for text states:

Set the content of each element in the set of matched elements to the specified text.

So positioning the text between the tags is in fact a feature of text, in fact that's the precise thing it is designed to do.

And it's not specific to the p tag. If you replaced p with any other tag you would get the exact same behavior, for example:

$caption = $("<div></div>"); // Create div element
$caption.text("Example"); // Set content (inside) of div to "Example"
// This will result in <div>Example</div>
Ashton Holgate
Ashton Holgate
6,021 Points

I see. Yes I do understand now.

I was a bit confused as I didn't read the Description. I went straight to the example and saw that p tags were being inserted which led me to think that tags needed to be inserted for this to work. Looking back with better understanding I realise the significance was that those p tags were being placed inside the div.

Thanks for clarifying!