jQuery Selector for Elements Currently in Focus
In jQuery, the selector used to target the element that currently has
user focus is the :focus pseudo-class selector. This
article explains how to select, verify, and manipulate focused elements
using $(':focus'), complete with direct code examples,
common use cases, and the vanilla JavaScript equivalent.
How to Use the
:focus Selector
The :focus selector finds any element that currently
holds focus on the page, such as an active text input, textarea, button,
or link.
To select whatever element currently has focus anywhere in the document:
var currentElement = $(':focus');To restrict the search to a specific type of element, combine
:focus with a tag or class selector:
// Selects an input element only if it currently has focus
var focusedInput = $('input:focus');
// Selects an element with the class "form-field" if it has focus
var focusedField = $('.form-field:focus');Checking if a Specific Element Has Focus
If you want to check whether a specific element is currently focused,
use jQuery's .is() method:
if ($('#username').is(':focus')) {
console.log('The username input is active.');
}Practical Examples
Applying Styles or Actions to the Focused Element:
// Change the background color of whatever element is currently active
$(':focus').css('background-color', '#eef');Retrieving the ID or Value of the Focused Element:
var activeId = $(':focus').attr('id');
var activeValue = $(':focus').val();Native JavaScript Equivalent
While jQuery's $(':focus') is convenient, modern
browsers support the standard DOM property
document.activeElement, which returns the currently focused
element natively without requiring jQuery:
// Native DOM equivalent
var activeElement = document.activeElement;
// Wrap it in jQuery if jQuery methods are needed
var $activeElement = $(document.activeElement);Using $(document.activeElement) is generally faster than
running a global $(':focus') selector search because it
retrieves the element directly from the browser's DOM tree.