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 2

Why the teacher put the "<div>"string in a JQuery? if there is no $, it works as well.

Why the teacher put the div string in a JQuery? if there is no $, it works as well.

Hi Yawei,

Could you be more specific with which piece of code you're referring to or which point in the video?

There are a few dollars signs in this code used for different reasons so I'm not sure which one you're thinking can be removed.

2 Answers

Ok, I get it now.

In your original question you stated that it still worked without that $ sign. Are you positive that it does? Because I would think it would cause an error when you later do $overlay.show();

In your first example you're only assigning a string to the $overlay variable. The string happens to contain the opening and closing div tags but it is still only a string and it does not represent a real div element.

If you call the .show() method on this string as in $overlay.show() it should produce an error because strings do not have a show method. This method is part of jQuery and can only be called on jQuery objects.

In the second example with the dollar sign and parentheses you are passing in a html string into the jQuery constructor. This will take the string and create an html div element and then wrap it in a jQuery object. Now all of jQuery's methods are available to use on this object.

$overlay.show(); now works because $overlay is storing a jQuery object and we can call the show() method on that.

Let me know if that clears it up for you.

Thank you, Jason! Now I understand.

You're welcome.

Yixi Guan
Yixi Guan
7,927 Points

Your comment is helpful. Thank you. I think many students including me are confused here is because the lack of explanation of "jQuery object". I would suggest the teacher to explain it in advance, thoroughly.

Sorry, my expression wasn't clear. In other words, my meaning is that what's the differences between

  var $overlay='<div></div>'    and    var $overlay=$('<div></div>' )  ? why does the teacher use the second one ?