$ Variable (Dollar Sign) in Chrome?
Solution 1:
This has changed yet again, even since just last year.
The devtools console provides $
as an alias to document.querySelector
, along with many other things; here's an excerpted list:
$(selector)
returns the reference to the first DOM element with the specified CSS selector. This function is an alias for thedocument.querySelector()
function.$$(selector)
returns an array of elements that match the given CSS selector. This command is equivalent to callingdocument.querySelectorAll()
.$_
returns the value of the most recently evaluated expression.- The
$0
,$1
,$2
,$3
and$4
commands work as a historical reference to the last five DOM elements inspected within the Elements panel or the last five JavaScript heap objects selected in the Profiles panel.
...and a bunch of others.
Note how it calls $
an alias of document.querySelector
, but says $$
is "equivalent" to calling document.querySelectorAll
. Neither seems to be literally true; $ === document.querySelector
is false
, and $$
returns an array, not a NodeList
.
Solution 2:
It is one of the Chrome Developer Tools functions (so not available from the page). You can see documentation for it on the Console page.
It gets an element by a selector.
Firefox implements something similar
Solution 3:
The existing answers are outdated, $
is not an alias for document.getElementById
or document.querySelector
, but a wrapper for querySelector
. This wrapper actually takes an optional second argument for the element to query the child of.
This family of functions is documented under the Console: Selecting Elements:
Selecting Elements
There are a few shortcuts for selecting elements. These save you valuable time when compared to typing out their standard counterparts.
$()
Returns the first element that matches the specified CSS selector. It is a shortcut fordocument.querySelector()
.
$$()
Returns an array of all the elements that match the specified CSS selector. This is an alias fordocument.querySelectorAll()
$x()
Returns an array of elements that match the specified XPath.
However, these values are only the default values in the console. If the page overwrites the variable by including something like jQuery, the console will use the value from the page itself, and something like $('p')
will return a jQuery object rather than just the first p
element.