Today I found code online like this.
Here's a simplified version of what I don't understand.
<div id="foo"></div>
$(foo) //gets the correct element
How does foo not throw an error and select the right DOM element?
Today I found code online like this.
Here's a simplified version of what I don't understand.
<div id="foo"></div>
$(foo) //gets the correct element
How does foo not throw an error and select the right DOM element?
Honestly, I did not know this was possible but it is a feature of javascript. You should read this stackoverflow answer which basically says, do NOT use this feature.
I don't have a detailed explanation but I'll say this. It has nothing to do with jQuery. This is purely a javascript feature.
Run this test to understand. Create an index.html file and then open up the console in developer tools. Type out the id name on the element and javascript will print out the javascript.
index.html
<html>
<body>
<div id="foo"></div>
</body>
</html>
In the console log, write out foo
and click enter. Chrome console should print out <div id="foo"></div>
.
In your example, you should fix the typos so you get a clearer understanding. I may not be using the official jQuery verbiage here, you should read the docs, but this should make some sense of the example.
These are not variables, they are jQuery objects.
The javascript elements like $( '#overlay' )
are calls to the jQuery function with a selector which can be the same as a CSS selector. The return value is a jQuery object, and jQuery's method .addClass()
is being invoked right away on the returned object.
In your example, the selectors are ids, but tag names, classes and pseudo classes work too, and you can even wrap javascript references to DOM elements in $( ... )
to use jQuery functions. jQuery returns an object that includes many member functions, not just the .addClass()
method shown here, and some selectors will return a collection not just a single item. For instance, $( 'a' )
returns a jQuery object with a reference to every link on the page.