Console tool utility functions and selectors

The Console Utilities API contains a collection of convenience functions for performing common tasks, such as:

  • Selecting and inspecting DOM elements.
  • Displaying data in a readable format.
  • Stopping and starting the profiler.
  • Monitoring DOM events.

These commands only work by entering them directly into the DevTools Console; you can't call these commands from scripts.

Summary

Function Description
$_ Returns the value of the most recently evaluated expression.
$0 - $4 Returns a recently selected element or JavaScript object.
$(selector) Query selector; returns the reference to the first DOM element with the specified CSS selector, like document.querySelector().
$$(selector, [startNode]) Query selector all; returns an array of elements that match the specified CSS selector, like document.querySelectorAll().
$x(path, [startNode]) Returns an array of DOM elements that match the specified XPath expression.
clear() Clears the console of its history.
copy(object) Copies a string representation of the specified object to the clipboard.
debug(function) When the specified function is called, the debugger is invoked and breaks inside the function on the Sources panel.
dir(object) Displays an object-style listing of all of the properties for the specified object, like console.dir().
dirxml(object) Prints an XML representation of the specified object, as displayed in the Elements tool, like console.dirxml().
inspect(object/function) Opens and selects the specified DOM element in the Elements tool, or the specified JavaScript heap object in the Memory tool.
getEventListeners(object) Returns the event listeners that are registered on the specified object.
keys(object) Returns an array containing the names of the properties belonging to the specified object.
monitor(function) Logs a message to the console that indicates the function name, along with the arguments passed to the function as part of a request.
monitorEvents(object[, events]) When one of the specified events occurs on the specified object, the event object is logged to the console.
profile([name]) Starts a JavaScript CPU profiling session with an optional name.
profileEnd([name]) Completes a JavaScript CPU profiling session and displays the results in the Memory tool.
queryObjects(Constructor) Returns an array of the objects that were created by the specified constructor.
table(data[, columns]) Logs object data, formatted as a table with column headings, for the specified data object.
undebug(function) Stops the debug of the specified function, so that when the function is requested, the debugger is no longer invoked.
unmonitor(function) Stops the monitoring of the specified function.
unmonitorEvents(object[, events]) Stops monitoring events for the specified object and events.
values(object) Returns an array containing the values of all properties belonging to the specified object.




Recently evaluated expression

Returns the value of the most recently evaluated expression.

Syntax:

$_

Example 1

  1. To open the Console tool: In Edge, click Settings and more, hover over More tools, and then select Developer tools. DevTools opens next to the present webpage. Click the Console tab.

  2. Click in the Console, type the expression 2+2, and then press Enter:

    In the following figure, a simple expression (2+2) is evaluated. The $_ property is then evaluated, which contains the same value:

    $_ is the most recently evaluated expression.

    2+2
    

    The simple expression (2+2) is evaluated as you type, and the Console outputs the number 4. The $_ property takes on the value 4.

  3. Type the expression $_, and then press Enter:

    $_
    

    The value of the $_ property is the value of the previously evaluated expression; the number 4.

    $_ represents the most recently evaluated expression, which is the number 4 from the previously entered statement.

Example 2

  1. To open the Console tool: In Edge, click Settings and more, hover over More tools, and then select Developer tools. DevTools opens next to the present webpage. Click the Console tab.

  2. Paste the following code into the Console, and then press Enter:

    ["john", "paul", "george", "ringo"]
    

    The evaluated expression is an array of names.

  3. Type the following code into the Console, and then press Enter:

    $_
    

    $_ represents the previously evaluated expression, which is an array of names.

  4. Type the following code into the Console, and then press Enter:

    $_.length
    

    The expression $_.length is evaluated to find the length of the array, which is the number 4. $_ now takes on the value 4, instead of an array of names.

  5. Type the following code into the Console, and then press Enter:

    $_
    

    $_ represents the previously evaluated expression, which is now the number 4.

    The value of $_ changes to the value of the previously evaluated expression.

$_ changes when new commands are evaluated.




Recently selected element or JavaScript object

Returns a recently selected element or JavaScript object.

$0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on. The $0, $1, $2, $3, and $4 commands work as a historical reference to the last five DOM elements that were inspected within the Elements tool, or the last five JavaScript heap objects that were selected in the Memory tool.

Syntax

$0

Example

In the following figure, an img element is selected in the Elements tool. In the Console drawer, $0 has been evaluated and displays the same element:

The $0 command.

The following image shows a different element selected in the same webpage. The $0 now refers to the newly selected element, while $1 returns the previously selected element:

The $1 command.




Query selector

Query selector; returns the reference to the first DOM element with the specified CSS selector, like document.querySelector().

This function is an alias for the document.querySelector() function.

Syntax

$(selector, [startNode])

Example

In the following figure, $('img') returns a reference to the first <img> element in the webpage:

$('img') returns a reference to the first  element in the webpage.

Right-click the returned result and then select Reveal in Elements Panel to find it in the DOM, or Scroll in to View to show it on the page.

Example

The following example returns a reference to the currently selected element and displays its src property:

$('img').src

Result:

The result of $('img').src.

This function also supports a second parameter, startNode, that specifies an element or node from which to search for elements. The default value of the parameter is document.

Example

$('img', document.querySelector('title--image')).src

Result: the first img element after the title--image element is found, and the src property of the img element is returned:

The result of $('img', document.querySelector('title--image')).src.

Note

If you are using a library such as jQuery that uses $, the functionality is overwritten, and $ corresponds to the implementation from that library.




Query selector all

Query selector all; returns an array of elements that match the specified CSS selector, like document.querySelectorAll().

This function is equivalent to document.querySelectorAll().

Syntax

$$(selector, [startNode])

Example

In the following example, $$() creates an array of all <img> elements in the current webpage, and displays the value of the src property for each element:

var images = $$('img');
for (each in images) {
    console.log(images[each].src);
}

Result:

Using $$() to select all images in the webpage and display the sources.

This query selector function also supports a second parameter, startNode, that specifies an element or node from which to search for elements. The default value of the parameter is document.

Example

The following, modified version of the previous example uses $$() to create an array of all <img> elements that appear in the current webpage after the selected node:

var images = $$('img', document.querySelector(`title--image`));
for (each in images) {
   console.log(images[each].src);
}

Here's the result. $$() selects all images that appear after the specified <div> element in the webpage, and displays the sources:

Using $$() to select all images that appear after the specified  element in the webpage and display the sources.

Note

Press Shift+Enter in the Console to start a new line without running the script.




XPath

Returns an array of DOM elements that match the specified XPath expression.

Syntax

$x(path, [startNode])

Example

In the following example, all of the <p> elements on the webpage are returned:

$x("//p")

Result:

Using an XPath selector.

Example

In the following example, all of the <p> elements that contain <a> elements are returned:

$x("//p[a]")

Result:

Using a more complicated XPath selector.

Similar to the other selector commands, $x(path) has an optional second parameter, startNode, that specifies an element or node from which to search for elements:

Using an XPath selector with startNode.




clear

Clears the console of its history.

Syntax

clear()

Example

clear()




copy

Copies a string representation of the specified object to the clipboard.

Syntax

copy(object)

Example

copy($0)




debug

When the specified function is called, the debugger is invoked and breaks inside the function on the Sources panel.

After the debugger is paused, you can then step through the code and debug it.

Syntax

debug(function)

Note

The Chromium issue #1050237 is tracking a bug with the debug() function. If you encounter the issue, try using breakpoints instead.

Example

debug("debug");

Result:

Breaking inside a function with debug().

Use undebug(function) to stop breaking on the function, or use the UI to turn off all breakpoints.

For more information on breakpoints, see Pause your code with breakpoints.




dir

Displays an object-style listing of all of the properties for the specified object, like console.dir().

This function is an alias for console.dir().

Syntax

dir(object)

Evaluate document.head in the Console to display the HTML between the <head> and </head> tags.

Example

In the following example, an object-style listing is displayed after using console.dir() in the Console:

document.head;
dir(document.head);

Result:

Logging 'document.head' with the 'dir()' function.

For more information, see console.dir() in the Console API.




dirxml

Prints an XML representation of the specified object, as displayed in the Elements tool, like console.dirxml().

This function is equivalent to console.dirxml().

Syntax

dirxml(object)




inspect

Opens and selects the specified DOM element in the Elements tool, or the specified JavaScript heap object in the Memory tool.

  • For a DOM element, this function opens and selects the specified DOM element in the Elements tool.
  • For a JavaScript heap object, this function opens the specified JavaScript heap object in the Memory tool.

Syntax

inspect(object/function)

Example

In the following example, the document.body opens in the Elements tool:

inspect(document.body);

Result:

Inspecting an element with inspect().

When passing a function to inspect, the function opens the webpage in the Sources tool for you to inspect.




getEventListeners

Returns the event listeners that are registered on the specified object.

The return value is an object that contains an array for each registered event type (such as click or keydown). The members of each array are objects that describe the listener registered for each type.

Syntax

getEventListeners(object)

Example

In the following example, all of the event listeners that are registered on the document object are listed:

getEventListeners(document);

Result:

Output of using getEventListeners(document).

If more than one listener is registered on the specified object, then the array contains a member for each listener. In the following figure, two event listeners are registered on the document element for the click event:

Multiple event listeners registered on the 'document' element for the 'click' event.

You can further expand each of the following objects to explore their properties. Here's an expanded view of the listener object:

Expanded view of listener object.




keys

Returns an array containing the names of the properties belonging to the specified object.

To get the associated values of the same properties, use values().

Syntax

keys(object)

Example

Suppose your application defines the following object:

var player1 = {"name": "Ted", "level": 42}

In the following code, the result assumes player1 was defined in the global namespace (for simplicity) before you type keys(player1) and values(player1) in the console:

keys(player1)

values(player1)

Result:

The keys() and values() commands.




monitor

Logs a message to the console that indicates the function name, along with the arguments passed to the function as part of a request.

Syntax

monitor(function)

Example

function sum(x, y) {
    return x + y;
}
monitor(sum);

Result:

Result of the monitor() function.

To end monitoring, use unmonitor(function).




monitorEvents

When one of the specified events occurs on the specified object, the event object is logged to the console.

You can specify a single event to monitor, an array of events, or one of the generic events types that are mapped to a predefined collection of events.

Syntax

monitorEvents(object[, events])

Example

The following code monitors all resize events on the window object:

monitorEvents(window, "resize");

Result:

Monitoring window resize events.

Example

The following code defines an array to monitor both resize and scroll events on the window object:

monitorEvents(window, ["resize", "scroll"]);

Specifying an event type

You can also specify one of the available types of events, strings that map to predefined sets of events. The following table shows the available event types and the associated event mappings:

Event type Corresponding mapped events
mouse "click", "dblclick", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "mousewheel"
key "keydown", "keypress", "keyup", "textInput"
touch "touchcancel", "touchend", "touchmove", "touchstart"
Ctrl "blur", "change", "focus", "reset", "resize", "scroll", "select", "submit", "zoom"

Example

In the following code, the key event type corresponding to key events on an input text field are currently selected in the Elements tool:

monitorEvents($0, "key");

Here's the sample output after typing a character in the text field:

Monitoring key events.




profile

Starts a JavaScript CPU profiling session with an optional name.

To complete the profile and display the results in the Memory tool, call profileEnd().

Syntax

profile([name])

Example

To start profiling, call profile():

profile("My profile")

To stop profiling and display the results in the Memory tool, call profileEnd().

Profiles can also be nested:

profile('A');
profile('B');
profileEnd('A');
profileEnd('B');

The result is the same, regardless of the order. The result appears as a Heap Snapshot in the Memory tool, with grouped profiles:

Grouped profiles.

Note

Multiple CPU profiles can operate at the same time, and you aren't required to close-out each profile in creation order.




profileEnd

Completes a JavaScript CPU profiling session and displays the results in the Memory tool.

To call this function, you must be running the profile() function.

Syntax

profileEnd([name])

Example

  1. Run the profile() function to start profiling.

  2. Run the profileEnd() function to stop profiling and display the results in the Memory tool:

    profileEnd("My profile")
    

For more information, see profile, above.




queryObjects

Returns an array of the objects that were created by the specified constructor.

The scope of queryObjects() is the currently selected runtime context in the Console.

Syntax

queryObjects(Constructor)

Example

  • queryObjects(promise) returns all instances of Promise.

  • queryObjects(HTMLElement) returns all HTML elements.

  • queryObjects(functionName) returns all objects that were instantiated using new functionName().




table

Logs object data, formatted as a table with column headings, for the specified data object.

For example, using this function, you can display a list of people's names as a table, in the Console.

Syntax

table(data[, columns])

Example

The following code displays a list of names using a table in the console, with the column headings defaulting to the variable names:

var names = {
    0: {
        firstName:  "John",
        lastName:  "Smith"
    },
    1:  {
        firstName:  "Jane",
        lastName:  "Doe"
    }
};
table(names);

Result:

The result of the table() function.




undebug

Stops the debug of the specified function, so that when the function is requested, the debugger is no longer invoked.

Syntax

undebug(function)

Example

undebug(getData);




unmonitor

Stops the monitoring of the specified function.

This function is used together with monitor().

Syntax

unmonitor(function)

Example

unmonitor(getData);




unmonitorEvents

Stops monitoring events for the specified object and events.

Syntax

unmonitorEvents(object[, events])

Example

The following code stops all event monitoring on the window object:

unmonitorEvents(window);

You can also selectively stop monitoring specific events on an object. For example, the following code starts monitoring all mouse events on the currently selected element, and then stops monitoring mousemove events (perhaps to reduce noise in the console output):

monitorEvents($0, "mouse");
unmonitorEvents($0, "mousemove");




values

Returns an array containing the values of all properties belonging to the specified object.

Syntax

values(object)

Example

values(object);




See also

Note

Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons Attribution 4.0 International License. The original page is found here and is authored by Kayce Basques (Technical Writer, Chrome DevTools & Lighthouse).

Creative Commons License. This work is licensed under a Creative Commons Attribution 4.0 International License.