Explain Codes LogoExplain Codes Logo

Valid to use <a> (anchor tag) without href attribute?

html
accessibility
javascript
semantics
Nikita BarsukovbyNikita Barsukov·Aug 18, 2024
TLDR
An **`<a>` tag without `href`** is **valid according to HTML5**, but it's essentially a **useless anchor**. To make it practical, add `onclick` for mouse users and `tabindex="0"` for keyboard navigation. **For instance**: ```html <a onclick="surprise();" tabindex="0">Magic Begins Here</a>

This nugget imitates a navigational link's behavior firing surprise(); on click and enabling keyboard-focus.

When & why to use non-navigable <a>?

An <a> without href often serves as a placeholder for actions like JS-driven events. It's perfectly fine to use them for modals or dropdowns. But do consider their accessibility. Always ensure they're coherent to both the keyboard and screen reader users.

Make <a> dynamic

When <a> needs to act as a <button>, add role="button" and JavaScript event listeners. Thus, you can enhance their semantics and also keep it interactive.

Keyboard friendliness

Remember our keyboard fanatics! Facilitate interaction for them by:

  • Giving tabindex="0" to make elements focusable.
  • Linking event listeners to the Enter or Space keys.
  • Turning <a> tag look clickable? Design does that. Customize it with CSS.
a[role="button"] { cursor: pointer; /* Mouse pointer appears on hover */ text-decoration: underline; /* Gives the link feel */ }

Craft accessible & semantic anchors

Optimize semantics

While <a> can be made to act like buttons, consider using <button> for actions. However, if the design or framework needs <a>, use role="button" to indicate its purpose to assistive tech users.

JavaScript functionalities

Data attributes such as data-toggle and data-target allow JS to interact with anchors without href. Do remember to maintain aria-expanded artstates to keep screen reader users informed about visibility changes.

ARIA for accessibility

When using icons inside anchor, add aria-hidden="true" indicating it's decorative and not content. Describe action for button-like links using aria-label.

<a role="button" onclick="doSomething();" aria-label="Start action" tabindex="0"> Start <i class="fa fa-play-circle" aria-hidden="true"></i> <!-- Not a real button, just a poser! --> </a>

Invalid but possible attributes

Certain attributes: target, download, rel, hreflang, and type shouldn't really work without href. But they do thanks to JS magic, which could spell trouble in the land of accessibility.