| title | Interact with the DOM using the Console |
|---|---|
| description | How to interact with the current webpage in the browser by using the Console tool. |
| author | MSEdgeTeam |
| ms.author | msedgedevrel |
| ms.topic | conceptual |
| ms.prod | microsoft-edge |
| ms.date | 04/13/2021 |
The Console tool is a great way to interact with the webpage in the browser. The Console is like a script-environment version of the Inspect tool.
To reference the header of the webpage:
-
Open the DevTools Console. To do this from a webpage, you can press
Ctrl+Shift+J(Windows, Linux) orCommand+Option+J(macOS). -
Type or paste the following code into the Console, and then press
Enter:document.querySelector('header')
-
In the Console, hover over the resulting HTML
<header>element, or pressShift+Tab. In the rendered webpage, DevTools highlights the header:
You can manipulate the webpage from the Console, as follows. In this example, you set a value in the DOM by using the Console, to affect the webpage styling: you add a green border around the header.
-
Press
Ctrl+Shift+J(Windows, Linux) orCommand+Option+J(macOS). The Console opens in DevTools, next to the present webpage. -
Paste the following code into the Console:
document.querySelector('header').style.border = '2em solid green'
A green border appears around the header:
Depending on the complexity of the webpage, it can be daunting to find the right element to manipulate. But you can use the Inspect tool to help you. Suppose you want to manipulate the Documentation region within the header of the rendered page:
To get a direct reference to the element that you want to manipulate:
-
In DevTools, click the Inspect tool, and then in the rendered webpage, hover over the element:
-
Click the element on the page, and DevTools jumps to the Elements tool.
-
Click the
...menu next to the element in the DOM tree: -
Right-click the element in the DOM tree and then select Copy > Copy JS Path.
-
In the Console, paste the JavaScript path that you copied, but don't press
Enteryet. -
Change the text of the link to
My Playground. To do that, add.textContent = "My Playground"to the JavaScript path that you previously pasted:
Use any JavaScript DOM manipulations you want in the Console. To make it more convenient, the Console comes with a few helper utility methods.
Many convenience methods and shortcuts are available to you as Console Utilities. Some of the methods are incredibly powerful and are much more effective than using console.log() statements.
The $ has special powers in Console, and you may remember that from jQuery.
-
$_stores the result of the last command. So, if you type2+2and pressEnter, and then type$_, the Console displays4. -
$0to$4is a stack of the last inspected elements.$0is always the newest one. So in the earlier example, you just select the element in the Inspect tool and type$0.textContent = "My Playground"to get the same effect. -
$x()allows you to select DOM elements using XPATH. -
$()and$$()are shorter versions of fordocument.querySelector()anddocument.querySelectorAll().
-
Enter the following code, which retrieves all the links in the webpage, and displays the links as a sortable table to copy and paste (for example, into Excel):
console.table($$('a'),['href','text']);
$$('a')is short fordocument.querySelectorAll('a').However, suppose you don't want to display all the information, but you want to grab it as data and then select only some of the data.
The
$$('a')shortcut helps with that: it selects the anchor links and all of the properties for each anchor link. But the problem is that you only want the anchor links and the related text, not all the properties of the anchor links.To solve that problem, the
$$shortcut has an interesting extra feature: instead of returning a pureNodeListlikedocument.querySelectorAll(), the$$shortcut gives you all of theArraymethods, includingmap(). -
Use the
map()method of theArrayobject to reduce the information to what you need:$$('a').map(a => { return {url: a.href, text: a.innerText} })
The above code returns an
Arrayof all the links, as objects withurlandtextproperties.You aren't done yet; several links are internal links to the webpage or have empty text.
-
Use the
filtermethod to get rid of the internal links:$$('a').map(a => { return {text: a.innerText, url: a.href} }).filter(a => { return a.text !== '' && !a.url.match('docs.microsoft.com') })
By manipulating the DOM through issuing statements in the Console, you can change these elements in the rendered webpage.
-
For example, enter the following code, which adds a green border around all external links:
$$('a[href^="https://"]').forEach( a => a.style.border = '1px solid green' )
Instead of writing complex JavaScript to filter results, use the power of CSS selectors.
To create a table of the src and alt information for all images on the webpage that aren't inline images:
-
Open the Console.
-
Paste the following code into the Console, and then press
Enter:console.table($$('img:not([src^=data])'), ['src','alt'])
Ready for an even more complex example? HTML webpages that are generated from Markdown tagging, like the present article, have automatic ID values for each heading, to allow you to deep-link directly to that section of the webpage. For example, a # New features h1 heading in the Markdown source file becomes <h1 id="new-features">New features</h1> in the HTML file.
To list all of the automatic headings to copy and paste:
-
Open the Console.
-
Copy and paste the following code:
let out = ''; $$('#main [id]').filter( elm => {return elm.nodeName.startsWith('H')} ).forEach(elm => { out += elm.innerText + "\n" + document.location.href + '#' + elm.id + "\n"; }); console.log(out);
The result is text that contains content for each heading followed by the full URL that points to it.
When developing in the Console, things can get messy. It can be difficult to select results to copy and paste. The following two utility methods help you:
-
copy()copies whatever you give it to the clipboard. Thecopy()method is especially useful when you mix it with$_, which copies the last result. -
clear()clears the Console.
Two other interesting utility methods of Console deal with event handling:
-
getEventListeners(node)lists all the event listeners of a node. -
monitorEvents(node, events)monitors and logs the events that happen on a node.
To list all of the event listeners that are assigned to the first form in the webpage:
-
In DevTools, open the Console.
-
Type or paste the following code into the Console:
getEventListeners($('form'));
When you monitor, you to get a notification in the Console every time something changes to the specified elements. You define the events you want to listen to as a second parameter. It's important for you to define the events that you want to monitor, otherwise any event happening to the element is reported.
To get a notification in the Console every time you scroll, resize the window, or when the user types in the search form:
-
In DevTools, open the Console.
-
Paste the following code into the Console:
monitorEvents(window, ['resize', 'scroll']); monitorEvents($0, 'keyup');
-
To log any key action on the currently selected element, focus on the search form in the header and press some keys.
-
To stop logging, remove the monitoring you set, enter the following code into the Console:
unmonitorEvents(window, ['resize', 'scroll']); unmonitorEvents($0, 'key');
You may find it useful to manipulate the DOM from the Console. You might soon run into the limitations of the Console as a development platform. The good news is that the Sources tool in DevTools offers a fully featured development environment. In the Sources tool, you can:
-
Store your scripts for the Console as snippets; see Run snippets of JavaScript on any webpage.
-
Run the scripts in a webpage by using a keyboard shortcut or the editor.

















