Search code examples
htmlaccessibilitytabindex

tabindex -1 not working for child elements


I have a div tag with some content getting loaded inside it. The content inside can have buttons, anchor elements, etc. which are focusable. I do not have control over the content but I can modify the 'div' tag attributes.

My problem is the focus still goes to the content (anchor, buttons, etc.) even if I specify the tabIndex -1 to the div tag.

<!-- HTML content here -->
<div tabindex="-1" id="externalContent">
  <div>
    ...
    <button>click me</button> <!-- Focus shouldn't come here -->
  </div>
</div>
<!-- HTML content here -->

Is there a way to skip the entire content while tabbing ? It's certainly not working with the above code.


Solution

  • Setting tabindex="-1" allows you to set an element’s focus with script, but does not put it in the tab order of the page. It also does not pull the children of something out of keyboard tab order.

    tabindex="-1" is handy when you need to move focus to something you have updated via script or outside of user action.

    If you are trying to remove an element from tabindex altogether, whether for screen readers or keyboard users, you will likely have to choose between one of these:

    1. Hide it altogether (via display: none),
    2. Use script on the element so that when it receives focus, the script shifts the focus somewhere else.

    Without context (a working URL, a reason that you want to do this), this sounds very much like the opposite of accessibility. I encourage you not to mess with focus unless you have a very good reason.