0

Most browsers support "press tab to jump to the next link (?)". The selected element usually gets highlighted. This is how it looks here on SE

enter image description here

If I press tab now it changes to this:

enter image description here

Can you emulate this using JavaScript? I want to do something like

document.getElementById('answer-sort-dropdown-select-menu').click();

but instead of click it should be select/highlight/focus etc.

You can emulate this by right clicking on an element and the press tab - then the next element (not the one you right clicked but the following) is highlighted.

Tried to google this but I don't know what it is called.


Update: Please note that I am not interested in the actual tab order, I am only interested in highlighting an element.

d-b
  • 695
  • 3
  • 14
  • 43
  • 1
    Does this answer your question? [Focus Next Element In Tab Index](https://stackoverflow.com/questions/7208161/focus-next-element-in-tab-index) – ControlAltDel Aug 01 '23 at 14:21
  • @ControlAltDel No, but the answer below does - if I can get it to work. See my comment. – d-b Aug 01 '23 at 19:53

1 Answers1

1

You can use the focus() method:

document.getElementById("focusButton").addEventListener("click", () => {
  document.getElementById("myTextField").focus();
});
<input id="myTextField" value="Text field." />
<button id="focusButton">Click to set focus on the text field</button>

As shown here.

  • I have tried this from the browser console `document.getElementById("headerMenu").focus({ focusVisible: true })` but nothing happens (in Chrome). I was expecting the element to be highlighted? I don't need to add an event listener if I just execute it from the console, do I? – d-b Aug 01 '23 at 19:52