I would like to find out, in JavaScript, which element currently has focus. I\'ve been looking through the DOM and haven\'t found what I need, yet. Is there a way to do this
There are potential problems with using document.activeElement. Consider:
Some text
Some text
Some text
If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.
The following function gets around this, and returns the focused node:
function active_node(){
return window.getSelection().anchorNode;
}
If you would rather get the focused element, use:
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}