How to determine which html page element has focus? [duplicate]

Possible Duplicate:
How do I find out which DOM element has the focus?

Is there a way in javascript to determine which html page element has focus?


Use the document.activeElement property.

The document.activeElement property is supported on Chrome 2+, Firefox 3+, IE4+, Opera 9.6+ and Safari 4+.

Note that this property will only contain elements that accept keystrokes (such as form elements).


Check out this blog post. It gives a workaround so that document.activeElement works in all browsers.

function _dom_trackActiveElement(evt) {
    if (evt && evt.target) { 
        document.activeElement = evt.target == document ? null : evt.target;
    }
}

function _dom_trackActiveElementLost(evt) { 
    document.activeElement = null;
}

if (!document.activeElement) {
    document.addEventListener("focus",_dom_trackActiveElement,true);
    document.addEventListener("blur",_dom_trackActiveElementLost,true);
}

Something to note:

This implementation is slightly over-pessimistic; if the browser window loses focus, the activeElement is set to null (as the input control loses focus as well). If your application needs the activeElement value even when the browser window doesn't have the focus, you could remove the blur event listener.


Just for the record, a little late, and of course not supported in old browsers:

var element = document.querySelector(":focus");

Should work on all elements (e. g. also anchors).


Maybe document.activeElement, don't know about browser support tho. Seems to work in Firefox and IE7, but I guess you have to try it in Opera and so on too.