Identifying the Focused DOM Element in JavaScript
Finding out which DOM element has the focus is crucial for enhancing user experience and controlling element interaction. In JavaScript, this can be achieved using the document.activeElement property.
Using document.activeElement
document.activeElement represents the currently focused element in the document. It returns the element that has the active focus, such as an input field, textarea, or button. This property is supported by all major browsers.
Example:
const focusedElement = document.activeElement; console.log("Focused element:", focusedElement.tagName);
Alternative Approaches for Older Browsers
In older browsers, there wasn't a direct way to determine the focused element. To emulate this detection, event handlers for "focus" and "blur" can be added to all form fields. When a field gains focus, its reference can be stored in a variable. Conversely, when a field loses focus, the variable can be cleared.
Blurring ActiveElement
If you want to remove the activeElement, you can use the blur() method. This changes the activeElement to the body element.
document.activeElement.blur();
Additional Resources
The above is the detailed content of How Can I Identify the Currently Focused DOM Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!