$ Variable in Chrome?

半世苍凉 提交于 2019-11-25 22:30:05

This has changed yet again, even since just last year.

The devtools console provides $ as an alias to document.querySelector, along with many other things; here's an excerpted list:

  • $(selector) returns the reference to the first DOM element with the specified CSS selector. This function is an alias for the document.querySelector() function.
  • $$(selector) returns an array of elements that match the given CSS selector. This command is equivalent to calling document.querySelectorAll().
  • $_ returns the value of the most recently evaluated expression.
  • The $0, $1, $2, $3 and $4 commands work as a historical reference to the last five DOM elements inspected within the Elements panel or the last five JavaScript heap objects selected in the Profiles panel.

...and a bunch of others.

Note how it calls $ an alias of document.querySelector, but says $$ is "equivalent" to calling document.querySelectorAll. Neither seems to be literally true; $ === document.querySelector is false, and $$ returns an array, not a NodeList.

It is one of the Chrome Developer Tools functions (so not available from the page). You can see documentation for it on the Console page.

It gets an element by a selector.

Firefox implements something similar

The existing answers are outdated, $ is not an alias for document.getElementById or document.querySelector, but a wrapper for querySelector. This wrapper actually takes an optional second argument for the element to query the child of.

This family of functions is documented under the Console: Selecting Elements:

Selecting Elements

There are a few shortcuts for selecting elements. These save you valuable time when compared to typing out their standard counterparts.

$() Returns the first element that matches the specified CSS selector. It is a shortcut for document.querySelector().

$$() Returns an array of all the elements that match the specified CSS selector. This is an alias for document.querySelectorAll()

$x() Returns an array of elements that match the specified XPath.


However, these values are only the default values in the console. If the page overwrites the variable by including something like jQuery, the console will use the value from the page itself, and something like $('p') will return a jQuery object rather than just the first p element.

Judging by the link to the dev tools it is now uses document.querySelector() rather than just getElementById().

https://developers.google.com/chrome-developer-tools/docs/console

It's just quick access to document.getElementById.

Ther're two selectors in Webkit inspectors, the same that Mootools one : $ and $$

You can find some informations on it, here

They're juste here to help you in debug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!