dave dave - 1 year ago 62
jQuery Question

How to get the focused element with jQuery?

Using jQuery, how can I get the input element that has the caret's (cursor's) focus?

Or in other words, how to determine if an input has the caret's focus?

Answer Source
// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:


And if you want a jQuery object wrapping the element: