74

How can I make an HTML <div> element receive focus, so elements will be put into focus when focus() is called on them?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
Chito Adinugraha
  • 1,220
  • 2
  • 15
  • 21
  • 6
    You mean, so the `div` element can receive focus? HTML `tabindex="0"` JS `elRef.tabIndex = 0;` – Fabrício Matté Apr 28 '13 at 09:33
  • Possible duplicate of [Is it possible to focus on a
    using javascript focus() function?](http://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function)
    – Tim Malone Jul 06 '16 at 04:38
  • Please read from https://gist.github.com/jamiewilson/c3043f8c818b6b0ccffd, not every html element is focusable by default. – Alan Dong Aug 09 '19 at 06:13

1 Answers1

133

Set the tabindex="0" on the div, on the assumption that you want the divs to receive focus, rather than child elements.

Updated the answer to add a JS Fiddle demo, showing a JavaScript means of achieving this:

var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++){
    divs[i].setAttribute('tabindex', '0');
}

JS Fiddle demo.

While composing the demo I found that tabindex="-1" allows the element to receive mouse-clicks to assign focus, but not keyboard events (through the tab button), however (and as implied in the comment, earlier, by Fabricio Matté, a tabindex="0" allows for both). So I've used that in the demo, and updated the original answer to reflect that change.

Behavior of tabindex="0" versus tabindex="-1" documented here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex

JHS
  • 1,423
  • 17
  • 29
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • `tabindex="-1"` also allows you to focus the element with javascript by using `element.focus()` – Seega Nov 17 '22 at 14:36