Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

You might think that when you bet on the web platform and rely on native HTML features, your website will be completely accessible. Unfortunately, this assumption is wrong in many cases.

If you want to learn about more inaccessible HTML features, a recent HTMHell article covered many of them. It's a great read!

This week, I've learned that even simple things, such as linking to local elements via id (<a href="#something">), require careful consideration not to cause accessibility problems.

What's the issue with local links?

document.activeElement is only set to focusable elements

I've been reading How To Avoid Breaking Web Pages For Keyboard Users and learned that some assistive technologies rely on document.activeElement.

The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.

For example, when you're jumping through a page via your keyboard's TAB key, document.activeElement will always reference the focused element. It can be links, buttons, inputs... you get the idea.

And that's great, but what happens when you follow a link pointing to an unfocusable element, like a skip link referencing the main element or a "scroll to top" link returning you to a blog's headline?

Then, there's nothing to focus, and the document.activeElement moves to body as a fallback. If assistive technology relies on document.activeElement, the context is lost. That's pretty poor UX. Ouch!

To resolve this issue, if you're targeting a container, headline or any other unfocusable element, make it focusable via tabindex="-1".

tabindex="-1" defines that an element is focusable but not reachable via sequential keyboard navigation. Learn more about tabindex on MDN.

And here's the fix in action.

a link target without tabindex
a link target with tabindex
Click the links above to see what document.activeElement becomes after interacting with a local link.


The fact that activeElement can only be a focusable element is pretty reasonable. Still, it's puzzling that simple web features like linking to another HTML element must be evaluated and carefully considered to keep everything intact and accessible.

It's another case of "writing good and accessible HTML is tougher than the web industry thinks". But if you're reading this blog, you probably know this already. 😉

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 8 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles