Search code examples
javascriptjqueryecmascript-6cross-browser

Is dollar sign defined in Javascript even without jQuery?


I know that $("...") is of course defined in jQuery (What is the meaning of "$" sign in JavaScript), and also that some people who don't use jQuery define $ = document.querySelector or $ = document.querySelector.bind(document).

In some cases (Firefox, Chrome), $ seems to be available in the developer console even without loading this library, or without defining $ manually: see the main answer of What is the dollar sign in Javascript, if not jQuery.

Question: can we assume in 2022 that $ is an alias in most browsers for document.querySelector and can we use it directly in our JS code?

I know caniuse.com but here neither https://caniuse.com/?search=%24 nor https://caniuse.com/?search=dollar helped.

Example: open a html file containing:

<html>
<head></head>
<body>
<div id="a">Hello world</div>
</body>
</html>

Open the developer console and do $('#a'): it works.


Solution

  • No you can't. It's only available in developer console in some browsers without importing jQuery library.

    See https://developer.chrome.com/docs/devtools/console/utilities/#querySelector-function:

    $(selector) returns the reference to the first DOM element with the specified CSS selector. When called with one argument, this function is an alias for the document.querySelector() function.

    Here is a simple example:

    console.log($('#div'));
    <div id="div"></div>