64
votes

How can you select an element that has current focus?

There is no :focus filter in jQuery, that is why we can use something like this:

$('input:focus').someFunction();
8
What are you actually trying to do so I can know if there is a better approachTStamper
Note that you can use $(':focus') to find the element currently focused in the current document.Alexis Wilke

8 Answers

153
votes

$(document.activeElement) will return the currently focused element and is faster than using the pseudo selector :focus.

Source: http://api.jquery.com/focus-selector/

123
votes
alert($("*:focus").attr("id"));

I use jQuery.

It will alert id of element is focusing.

I hope it useful for you.

32
votes

Really the best way to do it is to setup a handler for the onFocus event, and then set a variable to the ID of the element that has focus.

something like this:

var id;

$(":input").focus(function () {
     id = this.id;
});
5
votes

Have you tried

$.extend($.expr[':'], {
    focused: function(elem) { return elem.hasFocus; }
});

alert($('input :focused').length);
5
votes

If you use JQuery, you can write a selector like this:

$.expr[':'].focus = function(a){ return (a == document.activeElement); }

You can then select the currently focused element: $(":focus")

Not only form controls can have focus. Any html element with a tabindex can be focused in modern browsers.

4
votes

Lifted from the examples for the current jQuery version (1.7) docs:

$(elem).is(":focus");
1
votes

For checking element has focus or not.

if ($("...").is(":focus")) {
  ...
}
0
votes

Here is the CoffeeScript version of it. Based upon jmanrubia's code:

$.expr[':'].focus = (a) -> a is document.activeElement

You would also call it like so $(".:focus")