This content originally appeared on Hidde's blog and was authored by Hidde de Vries
When you build a Single Page Application, chances are that you manage some of the focus
through script. For debugging, it can be super useful to log the currently focused element to the Dev Tools Console.
Logging the focused element
The focused element is known in the DOM as document.activeElement
, so you can just console.log()
that if you want to know what the currently focused element is.
Logging it as it changes
Thanks to Eva, I recently learned a way to log the active element as it changes:
document.addEventListener('focusin', function() {
console.log('focused: ', document.activeElement)
}, true);
The focusin
event is like focus
, but it bubbles, so when any element within document
receives focus, focusin
bubbles all the way up to document
.
When I posted this on Twitter, Christian Schaefer helpfully pointed out that, although focus
does not bubble, it can be intercepted when the capturing
flag (addEventListener
’s third argument) is set to true
. Phil Walton then added that focus
fires also for non-interactive elements and when the window
receives focus. Even better!
So this is what you could use to log the active element when it changes:
document.addEventListener('focus', function() {
console.log('focused: ', document.activeElement)
}, true);
Also relevant: PPK’s Delegating the focus and blur events, over 10 years old, in which he explains that lack of bubbling in focus
makes sense, because we would not want it to bubble to window
, as the `window’ having focus means that the user has focused the entire browser window.
This content originally appeared on Hidde's blog and was authored by Hidde de Vries

Hidde de Vries | Sciencx (2019-01-30T00:00:00+00:00) Console logging the focused element as it changes. Retrieved from https://www.scien.cx/2019/01/30/console-logging-the-focused-element-as-it-changes/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.