You can only focus on one element at a time. If you look at a page visually, you can tell what the focused element is by their styles. In JavaScript, you can tell what the focused element is with document.activeElement.
Note: Buttons do not get focus if you click on them in Firefox (Mac) or Safari. I wrote about this strange behavior in this article.
I also recommend adding this code at the top of your JavaScript file. This piece of code normalizes the differences between browsers when you click on them.
document.addEventListener('click', event => {
if (event.target.matches('button')) {
event.target.focus()
}
})
Detecting the focused element automatically
Chrome devtools have a tool called Live Expression. You can use it to tell you what the focused element is at any point.
To use Live Expression, you open Chrome devtools. Click on Console. Then click on the eye icon.
After clicking on the eye icon, a box with the word “Expression” will pop up.
Replace “Expression” with the expression you want to watch for. In this case, we set the expression to document.activeElement.
The document.activeElement expression will then update automatically.