85

Is it possible to programmatically change the value of the document.activeElement property in JavaScript?

Piper
  • 1,266
  • 3
  • 15
  • 26
mgamer
  • 13,580
  • 25
  • 87
  • 145

2 Answers2

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
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
  • 33
    element.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
    Looks like it should be `tabIndex` – writofmandamus Feb 28 '19 at 20:25
  • 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