What is the current element? (document.activeElement)
console.log(document.activeElement);
I use document.activeElement
constantly when I do accessibility work (getting things to work with screenreaders like NVDA, JAWS or VoiceOver). document.activeElement
contains the current element that is in focus on a page.
You can easily debug it with a live expression in the chrome console:
Here is a small demo to play with – try clicking or tabbing around the buttons and inputs:
const el = document.createElement('el');
el.innerHTML = `
<button class="one">one</button>
<button class="two">two</button>
<button class="three">three</button>
<button class="four">four</button>
<hr>
<input type="text" placeholder="type...">
<hr>
<input type="range">
`;
document.body.appendChild(el);
let lastActive;
setInterval(() => {
if (document.activeElement != lastActive) {
lastActive = document.activeElement;
console.log(lastActive.outerHTML);
}
// no need to update 60fps
}, 100);