How do I find out which DOM element has the focus?
The reason I was looking for this:
I’m trying to make keys like the arrows and
enter navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I’ve got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
document.activeElement, it is supported in all major browsers.
Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a “focus” event handler to all fields and record the last-focused field in a variable. Add a “blur” handler to clear the variable upon a blur event for the last-focused field.
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+.
This statement will get you the currently focused element.
document.activeElement is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to
querySelector (if that is supported). It’s also worth mentioning that
document.activeElement will return
document.body if no element is focused — even if the browser window doesn’t have focus.
The following code will work around this issue and fall back to
querySelector giving a little better support.
var focused = document.activeElement; if (!focused || focused == document.body) focused = null; else if (document.querySelector) focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the
activeElement property. See this jsperf.com test.