Is it possible to programmatically change the value of the document.activeElement
property in JavaScript?
Asked
Active
Viewed 9.6k times
85
2 Answers
114
In IE, use the setActive()
method of the element that you want to be the active element. In other browsers that support activeElement
, you can use the focus()
method of the element, so long as the element is capable of receiving the focus (form elements, editable elements, elements with tabindex
set).
If you want to set the activeElement back to the default (the <body>
element in most browsers), just call the active element's blur()
method:
document.activeElement.blur();

Tim Down
- 318,141
- 75
- 454
- 536
-
Let's take the page at jquery.com as an example. When you enter the page and check document.activeElement in FireBug you get "". Then let's say that you change activeElement do some link element (). How can you after that reset activeElement to the previous one (body). I can't do it using document.body.focus(); – mgamer Oct 22 '10 at 09:45
-
4just remember to set tabindex="-1" for div elements – g00fy Mar 17 '14 at 09:28
-
@g00fy: In what circumstances? – Tim Down Mar 17 '14 at 12:27
-
1@TimDown when you want to focus on "non focusable" DOM nodes, like a div. If `tabindex="-1"` is set in a regular tag, it can be focused with `.focus()` – Darlan Alves Jul 18 '19 at 11:17
35
You can just .focus()
the element you want and it'll be the new document.activeElement
.

Nick Craver
- 623,446
- 136
- 1,297
- 1,155
-
33element.focus only has an effect in Chrome 55 if element.tabindex is defined. Divs by default do not have a tabindex, so by default div.focus() has no effect. At any time before calling focus, just set element.tabindex to some value, like '-1'. Then call element.focus. You will see that now element === document.activeElement, which now means that scroll keys like up/down will apply to the currently active element. Confusing! – Josh Nov 11 '16 at 17:30
-
1
-
My activeElement was an iframe and this didn't work for me on Chrome 84. `.blur()` did though. – Boris Verkhovskiy Jul 25 '20 at 20:53