DEV Community

Mike E
Mike E

Posted on • Updated on

How to inspect transient DOM elements

There are certain situations in web applications where a UI element will appear/disappear from the screen and it is challenging to inspect it. This typically occurs when an element's presence in the DOM is based on focus or hover state which changes when you attempt to inspect it. In this article, I'll cover a couple ways to overcome this.

The OK way

An easy way to inspect an element which may be satisfactory in many situations is to use setTimeout() in combination with debugger; to effectively freeze the DOM, allowing you to then inspect anything at your leisure. The debugger; statement (documented here) invokes the Javascript debugger and completely pauses execution. When used in the callback of a setTimeout() timer, you can "schedule" the DOM to freeze after you've gotten the UI ready for inspection.

Here is a CodeSandbox example where you can play around with this technique. In this example, if you click on the <input>, an options menu will appear. If our goal was to inspect one of the options in the menu, we'd have to contend with the fact that the menu disappears when we click anywhere outside of the menu.

To test this solution, open up the Developer Tools and add the following code to the Console tab:

setTimeout(() => { debugger; }, 3000)
Enter fullscreen mode Exit fullscreen mode

Once we submit this command in the console, you'll have three seconds to open the menu, before the execution is paused and the DOM is frozen.

frozen DOM

One drawback of this approach is the DOM is completely frozen. This means that if we wanted to do something like check the hover behavior on one of the options menu, we couldn't.

The better way

A better way is to leverage Chrome's "Emulate a focused page" option in Developer Tools. You can quickly enable this option by using Chrome's command palette by pressing Control+Shift+P on Windows/Linux or Command+Shift+P on Mac. Once open, start typing "Emulate a focused page" or "emfo" for short.

command palette - emulate a focused page

Once enabled, you can hit the "Select an element in the page to inspect it" button in Developer Tools.

inspector button

Lastly, click on the options menu or one of the options. You'll notice that the menu does not disappear and you can even see hover styles.

emulating a focused page

Top comments (2)

Collapse
 
pavelee profile image
Paweł Ciosek

Simple and practical

Collapse
 
dgreene1 profile image
Dan Greene

This is amazing. Every once in a while you learn something that totally changes how you work. This is one of those! 🎉🥳