)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

What is the current element? (document.activeElement)

  1. 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:

  1. const el = document.createElement('el');
  2. el.innerHTML = `
  3.   <button class="one">one</button>
  4.   <button class="two">two</button>
  5.   <button class="three">three</button>
  6.   <button class="four">four</button>
  7.   <hr>
  8.   <input type="text" placeholder="type...">
  9.   <hr>
  10.   <input type="range">
  11. `;
  12. document.body.appendChild(el);
  13.  
  14. let lastActive;
  15. setInterval(() => {
  16.   if (document.activeElement != lastActive) {
  17.     lastActive = document.activeElement;
  18.     console.log(lastActive.outerHTML);
  19.   }
  20.  
  21. // no need to update 60fps
  22. }, 100);
snippet.zone ~ 2021-24 /// {s/z}