Search code examples
javascripthtmlaccessibilitysemantics

HTML Semantics - Button acting as an anchor


I'm mainly interested in the a11y aspects

So as you might be aware, sometimes you might wish to have a button that acts as an anchor.
These are 4 ways (I can think of) of approaching this issue:

1. Button inside an anchor element

<a href="//redirection"><button>Button</button></a>

2. Anchor inside button element

<button><a href="//redirection">Button</a></button>
<!-- Also should it be a href or button onclick (?) -->

3. Anchor styled as a button (without a button element)

<a class="buttonLike" href="//redirection">Button</a>

4. Button acting as a redirection (without an anchor element):

const button = document.getElementById('button')
button.addEventListener('click', () => {
  window.location.href = "//redirection"
})

<button id="button">Button</button>

I've tried to find an answer to this myself. Closest I could find was this excerpt:
According to the MDN anchor spec, which states the following:

Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.

Unfortunately this doesn't help me too much. Basically all it states is you should not use the third approach (anchor styled as a button) if you don't mean to provide a real link to it, which is not what this question is about.

Is there any official WCAG on this subject matter that I was unable to find or?


Solution

  • Option 1 is not valid HTML.

    Option 2 is not valid HTML.

    Option 3 is the correct choice here.

    Option 4 is semantically incorrect.

    Semantics are one of if not the most important aspects of accessibility.

    There are two things at play which dictate option 3.

    The first is that an anchor should be used only to jump to sections and to navigate between pages.

    The second is that a button should perform actions on the same page.

    Now if you want to style a call to action link to look like a button that is fine but make sure you use the correct semantics, but make sure that CTA leads to a new page or it isn't semantically correct.

    And although it is swearing on StackOverflow to mention SEO, a hyperlink rather than a JavaScript redirection will be far better.