flowerszhong
flowerszhong

Reputation: 307

Why can't I access Chrome built-in function $?

Type $ in Chrome console then return:

$;
function () { [native code] }

And to get a DOM element:

$("container");
<div class=​"container" id=​"container">​…​</div>​

But it cannot work in script block:

window.onload = function  (argument) {
    var container = $("container");
    Uncaught ReferenceError: $ is not defined
}

Upvotes: 3

Views: 335

Answers (2)

Justin Niessner
Justin Niessner

Reputation: 245399

You're getting the error because that, while the Google Chrome Console has its own $ shortcut operator, it's not available to the original window:

Chrome Developer Tools: Console

If you want functionality like that in your application, you'll need to include some other library (jQuery is the popular choice around here but there are others like Prototype, MooTools, etc) or you could simply rip the function out of the jQuery console if that's all you need.

Upvotes: 11

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

By looking at the actual contents of the $ function in the Chrome console, one can infer that it is in fact nothing more than a "toolbox function" built into the Console by the Chrome developers. Since it's in the the console, you can't access it from the window available to you.

Said contents:

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

Upvotes: 3

Related Questions