Understanding the Difference Between $$ and $ in Chrome Console

The Chrome Developer console is a powerful tool that allows developers to debug and inspect their web applications. It provides a variety of features, including the ability to execute JavaScript code, view network activity, and examine the DOM (Document Object Model).

One feature that may be unfamiliar to some developers is the use of $$ and $ as shorthand for accessing elements in the DOM. In this article, we will explore the difference between these two symbols and how they can be used in the Chrome console.

What is $ in Chrome Console?

The $ symbol is an alias for the document.querySelector function in the Chrome console. This function allows you to select the first element on the page that matches a given CSS selector. For example:

Copy code$("#my-element")

This will return the first element on the page with the ID “my-element”.

What is $$ in Chrome Console?

Like $, $$ is also an alias, but it is for the document.querySelectorAll function. This function allows you to select all elements on the page that match a given CSS selector. For example:

Copy code$$(".my-elements")
$$ and $ in Chrome Console

This will return a NodeList containing all elements on the page with the class “my-elements”.

How to Use $ and $$ in Chrome Console

To use $ or $$ in the Chrome console, simply type the symbol followed by a CSS selector in parentheses. For example:

Copy code$("#my-element")

You can also chain other methods to the end of the $ or $$ call, just like you would with a normal DOM selection. For example:

Copy code$("#my-element").innerHTML = "Hello, world!";
$$(".my-elements").forEach(element => console.log(element.innerHTML));

Frequently Asked Questions

Can I use $ and $$ in my scripts?

Yes, you can use $ and $$ in your scripts just like you would in the console. However, it is generally considered best practice to use the full document.querySelector and document.querySelectorAll functions in your scripts, as it is more explicit and may be easier for other developers to understand.

Can I use $ and $$ in other browsers?

$ and $$ are specific to the Chrome console and will not work in other browsers. However, other browsers may have their own console aliases or shortcuts that you can use. For example, Firefox has the $0 and $1 variables, which refer to the last two selected elements in the console.

Are there any other console shortcuts I should know about?

Yes, there are many other console shortcuts that can be useful for developers. Here are a few examples:

  • $_: The result of the last expression evaluated in the console
  • $x: Select an element using an XPath expression
  • clear(): Clear the console
  • dir(): Print an interactive list of the properties of an object

$ and $$ are useful aliases in the Chrome console

Leave a Comment