How do I find out which DOM element has the focus?

后端 未结 16 1269
悲&欢浪女
悲&欢浪女 2020-11-22 03:12

I would like to find out, in JavaScript, which element currently has focus. I\'ve been looking through the DOM and haven\'t found what I need, yet. Is there a way to do this

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:39

    Use document.activeElement, it is supported in all major browsers.

    Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.

    If you need to remove the activeElement you can use blur; document.activeElement.blur(). It will change the activeElement to body.

    Related links:

    • activeElement Browser Compatibility
    • jQuery alternative for document.activeElement

提交回复
热议问题