2

I know the $ is part of JQuery's lib and I am surprised that it exist as an object in the browser console. (I'm not sure if it's just my environment)

but I can do.. $('#id') to get the dom id of an element. Where I have been always using document.getElementById('id') to get an element before.

I can't find references to $ on MDN.

Is the $ now available everywhere and is it ok to use when getting elements with native javascript or should I still use document.getElementById?

P.S. I know I don't have jQuery being used as $( window ).height(); won't work until I paste the following in my console in a local html file with no external resources attached.

(function(d, script) {
    script = d.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.onload = function(){
        // remote script has loaded
    };
    script.src = 'http://code.jquery.com/jquery-3.2.1.min.js';
    script.crossorigin = 'anonymous'
    d.getElementsByTagName('head')[0].appendChild(script);
}(document));
Jonathan002
  • 9,639
  • 8
  • 37
  • 58
  • 2
    `I can't find references to $ on MDN.` - you mean this? https://developer.mozilla.org/en-US/docs/Tools/Web_Console/The_command_line_interpreter#Helper_commands - note, these helper commands **only work in the developer tools console** - they are not "available" to javascript in a web page sense – Jaromanda X Jul 30 '17 at 05:35
  • Yeah I did try to type $ in mdn search and got an empty search result. Thanks for this. – Jonathan002 Jul 30 '17 at 05:38
  • I searched for *developer tools console commands* :p – Jaromanda X Jul 30 '17 at 05:39

1 Answers1

2

In fact, some browser consoles add a 'shorthand' function named '$' to get DOM elements. This is not jQuery but only uses the same function name. (see $ Variable in Chrome?)

jQuery adds a lot of functionality which was useful for older browsers. In the meantime, almost all browsers have most of this functionality already build in.

So, if you don't need jQuery for some other things than getting a DOM element, you should not include jQuery. Have a look at http://youmightnotneedjquery.com for more detailed information.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • 1
    Also, this is there is documentation for the `$` in the console API here: https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference – Wesley Smith Jul 30 '17 at 05:45