Is it possible to focus on a <div> using JavaScript focus() function? Is it possible to focus on a <div> using JavaScript focus() function? javascript javascript

Is it possible to focus on a <div> using JavaScript focus() function?


Yes - this is possible. In order to do it, you need to assign a tabindex...

<div tabindex="0">Hello World</div>

A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

document.getElementById('test').onclick = function () {    document.getElementById('scripted').focus();};
div:focus {    background-color: Aqua;}
<div>Element X (not focusable)</div><div tabindex="0">Element Y (user or script focusable)</div><div tabindex="-1" id="scripted">Element Z (script-only focusable)</div><div id="test">Set Focus To Element Z</div>