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 trialYAWEI SONG
9,168 PointsWhy 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.
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsOk, 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.
YAWEI SONG
9,168 PointsThank you, Jason! Now I understand.
Jason Anello
Courses Plus Student 94,610 PointsYou're welcome.
Yixi Guan
7,927 PointsYour 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.
YAWEI SONG
9,168 PointsSorry, 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 ?
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi 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.