Search code examples
javascriptjquerygoogle-chrome-console

When did the $ become natively available to the console?


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));

Solution

  • 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.