SkillGG
SkillGG

Reputation: 686

What does $ function means in vanilla (no libraries) JS?

I was wondering what does $ sign function means.

Is it just a shortcut to document.querySelector or does it have more uses.

I went to about:blank page and typed in console $.

Result in Firefox was:

function()

and in Chrome:

ƒ $(selector, [startNode]) { [Command Line API] }

It works as shortcut to document.querySelector() but I am not sure what it's called and what is browser support for this.

There is also $$ function that works as document.querySelectorAll(),

$_ that stores last $/$$ function result,

$0 that is just reference to document.body (I think)

and $x that i assume is XPath query becuase of xpath argument:

ƒ $x(xpath, [startNode]) { [Command Line API] }

(chrome output when typing $x in console)

Upvotes: 0

Views: 607

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21475

As the "[Command Line API]" message suggests, it's a convenience function built into the browser, rather than a part of vanilla javascript.

For Chrome, for example:

The Console Utilities API contains a collection of convenience functions for performing common tasks: selecting and inspecting DOM elements, displaying data in readable format, stopping and starting the profiler, and monitoring DOM events. https://developers.google.com/web/tools/chrome-devtools/console/utilities

Safari and Firefox appear to support the same set of functions as Chrome; I believe (but am not certain) that this is by consensus rather than an actual standard.

These functions will only work in the developer console; they are not usable elsewhere.

console.log($) // will throw "ReferenceError: Can't find variable: $"

The $ character itself has no special significance in javascript, and can be used as any other character glyph:

var $ = "hello"
var a$b = "world"
console.log($, a$b)

$ = function() {console.log("This will confuse jQuery users, probably not a great idea")}
$()

Upvotes: 5

Hero Wanders
Hero Wanders

Reputation: 3292

You have found the non-standardized identifiers built into each browser's developer tools. They are not part of vanilla JS.

Please notice that you can't use these helpers in a regular script. Depending on the libraries in use or the context of writing those identifiers, they may have a completely different meaning, compared to the builtin helpers since they can be assigned arbitrarily there.

Upvotes: 2

Related Questions