Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Console and Sources

Console Utilities and Live Expressions

Use the Console Utilities API: $0, $_, $, $$, $x, copy, monitor, debug, getEventListeners and queryObjects, with runnable stand-ins that model how they work.

The Console is a normal JavaScript prompt with an extra set of helpers that exist only inside DevTools. They are called the Console Utilities API. They save typing, give you quick access to what you selected in the Elements panel, and let you watch functions and events. They are not part of the web page, so never use them in your own code.

Selecting elements: $0 to $4, $, $$, $x

  • $0 is the element currently selected in the Elements panel. $1 is the one selected before it, up to $4.
  • $(selector) is a short form of document.querySelector. Returns the first match.
  • $$(selector) is document.querySelectorAll, but returns a real array, so .map, .filter and .length work.
  • $x(path) evaluates an XPath expression and returns an array of matches, for example $x("//a[@href]").

If the page itself defines a global named $ (for example jQuery), the page's definition wins in code you type, and the utility $ is replaced. Use document.querySelector in that case.

Common one-liners:

JavaScript
$$("img").filter(img => !img.alt)            // images without alt text
$$("a").map(a => a.href)                      // every link target
$0.getBoundingClientRect()                    // size of the selected node
$$("*").filter(el => el.scrollWidth > innerWidth)  // elements wider than the screen

That last line is a classic for finding the element that causes a horizontal scrollbar.

$_ and history

$_ holds the result of the last expression you ran. This is useful when you forgot to assign the value:

JavaScript
document.querySelectorAll("li")   // NodeList(8)
Array.from($_)                    // now an array

Press Up and Down to move through your command history; it is kept between sessions. Ctrl+R-style search is not available, but typing and pressing Up finds matching earlier commands.

Stand-in: how $0 and $_ behave

The next stand-in models the history that $0..$4 and $_ keep. It is only a model; real DevTools gets the selected nodes from the Elements panel.

JS Stand-in: selection history and $_

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Inspecting, copying and monitoring

  • copy(value) puts any value on your clipboard: objects become formatted JSON, strings are copied as text, DOM elements as HTML. Great for taking data out of a page: copy($$("tr").map(r => r.innerText)).
  • inspect(object) opens an element in Elements or an object in the Sources/Memory area.
  • clear() clears the console, like console.clear().
  • keys(obj) and values(obj): shorthand for Object.keys and Object.values.
  • table(data): like console.table.
  • dir(obj) and dirxml(node): object tree and element markup views.

Functions that watch behavior:

  • monitor(fn) logs a message every time fn is called, with its arguments. unmonitor(fn) stops.
  • monitorEvents(target, [types]) logs events on a target, for example monitorEvents($0, "click") or monitorEvents(window, "resize"). Use event groups like "mouse", "key", "touch", "control". unmonitorEvents(target) stops.
  • getEventListeners(target) returns an object with the listeners attached to a target, grouped by event type.
  • debug(fn) sets a breakpoint on the first line of fn; undebug(fn) removes it. The next time fn runs, execution pauses in the Sources panel.
  • queryObjects(Constructor) returns all live objects created by a constructor (a memory debugging aid).
  • profile() and profileEnd() start and stop a CPU profile (older tool; the Performance panel is preferred now).

Utilities that work with the clipboard or other browser features may need the page to have focus. If copy() appears to do nothing, click once in the Console and try again.

Stand-in: monitor a function

monitor(fn) wraps a function so each call is logged. You can model it in a few lines. This is a teaching version, not DevTools' implementation.

JS Stand-in: monitor(fn)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real monitor does not require you to reassign the function: DevTools instruments the original. The visible effect, a line saying function applyDiscount(80, 25) called, is the same.

Live expressions

At the top of the Console is an eye icon: Create live expression. Type an expression such as document.activeElement, window.scrollY or performance.memory.usedJSHeapSize and it shows a continuously updating value (about every 250 ms). Live expressions persist while DevTools is open and are a clean alternative to logging in a loop.

Examples:

  • document.activeElement shows which element has focus, ideal for focus-order bugs.
  • window.innerWidth shows the viewport width as you resize.
  • localStorage.length or a specific key's value while you click around the app.
  • $$("li").length to see a list grow as items load.

Stand-in: a live expression loop

A live expression is just a function that is evaluated repeatedly and displayed. This stand-in polls a counter-based expression a few times to show the idea, using timers that finish quickly.

JS Stand-in: live expressions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Safety and good habits

  • Do not paste code you do not understand into the Console. Social-engineering scams ask people to paste scripts that steal accounts. Chrome shows a warning about this for a reason.
  • Variables you create (const x = 1) live in the page's global scope while DevTools is open; reload clears them.
  • A top-level await works at the Console prompt: await fetch("/api/user").then(r => r.json()).
  • Multi-line input: press Shift+Enter for a new line and Enter to run.
  • To run code in an iframe, change the JavaScript context selector at the top of the Console.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $0 refer to?

    $0 is the most recently selected node; $_ is the last evaluated result.
  2. 2. Which utility logs a message each time a function is called?

    monitor(fn) logs each call with arguments; debug(fn) sets a breakpoint instead.
  3. 3. What is the difference between $$('li') and document.querySelectorAll('li')?

    $$ returns an Array, so array methods like map and filter work directly.
  4. 4. Where do the Console Utilities API functions work?

    They are injected by DevTools into the Console and are not available to the page's own code.

Summary

  • $0, $_, $, $$ and $x select elements and reuse results quickly.
  • copy(), monitor(), monitorEvents(), getEventListeners() and debug() help with data export and behavior tracing.
  • Live expressions watch values without a logging loop.
  • Utilities exist only inside DevTools; never paste unknown code.

Next: The Sources Panel and Breakpoints