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 trialadammccann
Python Web Development Techdegree Student 12,554 PointsWhy can't $('<div id="overlay"></div>') just be replaced with $('#overlay') ...?
I would've thought that $('#overlay') would be specific enough to grab the overlay element...I mean, that's what this bit of jQuery is doing, right? Grabbing the overlay element and assigning it to the $overlay variable?
3 Answers
Steven Parker
231,236 PointsThe first one creates a new element, the second one selects an existing one.
When you write $('<div id="overlay"></div>')
you are creating a new element which has the ID of "overlay". I would expect that in later code this element would be added to a document which did not have an element with that ID already.
On the other hand $('#overlay')
will select an element that already exists in the document that has the ID of "overlay". Nothing new is created.
Sergey Blokhin
9,612 PointsWhy do we need to use $('')? can we create variable like this var $overlay = '<div id="overlay"></div>'; ?
Steven Parker
231,236 PointsSure, but your new variable will contain an ordinary string, not a jQuery object. And the convention for naming variables is that you only start the name with a dollar sign ($
) when it is used to hold jQuery objects, so that would not be "good practice" naming for a string variable.
Sergey Blokhin
9,612 PointsThank you Steven. Also what if I already have the <p></p> with a description for a photo. How do I take the text from it and assign it to overlay as a caption text?