Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select currently focused element

I'd like to find the currently focused element in the whole document. I tried using the :focus pseudoclass introduced with jQuery 1.6:

$(document).find(":focus")

But $(document).find(":focus").length always returns 0

like image 753
Valentino Avatar asked Dec 21 '22 02:12

Valentino


1 Answers

You should be able to use the activeElement property of the document:

var focus = $(document.activeElement);

If you look at the jQuery documentation for :focus it makes this perfectly clear:

If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

It's worth noting that if no element currently has focus, activeElement will refer to the body.

like image 151
James Allardice Avatar answered Jan 02 '23 01:01

James Allardice