org.sonar.l10n.javascript.rules.javascript.S6844.html Maven / Gradle / Ivy
The <a>
tag in HTML is designed to create hyperlinks, which can link to different sections of the same page, different pages, or
even different websites. However, sometimes developers misuse <a>
tags as buttons, which can lead to accessibility issues and
unexpected behavior.
This rule checks that <a>
tags are used correctly as hyperlinks and not misused as buttons. It verifies that each
<a>
tag has a href
attribute, which is necessary for it to function as a hyperlink. If an <a>
tag
is used without a href
attribute, it behaves like a button, which is not its intended use.
Using the correct HTML elements for their intended purpose is crucial for accessibility and usability. It ensures that the website behaves as
expected and can be used by all users, including those using assistive technologies. Misusing HTML elements can lead to a poor user experience and
potential accessibility violations.
Compliance with this rule will ensure that your HTML code is semantically correct, accessible, and behaves as expected.
Why is this an issue?
Misusing <a>
tags as buttons can lead to several issues:
- Accessibility: Screen readers and other assistive technologies rely on the correct use of HTML elements to interpret and interact with the
content. When
<a>
tags are used as buttons, it can confuse these technologies and make the website less accessible to users with
disabilities.
- Usability: The behavior of
<a>
tags and buttons is different. For example, buttons can be triggered using the space bar,
while <a>
tags cannot. Misusing these elements can lead to unexpected behavior and a poor user experience.
- Semantic correctness: Each HTML element has a specific purpose and meaning. Using elements for purposes other than their intended use can make
the code harder to understand and maintain.
- SEO implications: Search engines use the structure and semantics of HTML to understand and rank web pages. Misusing HTML elements can
negatively impact a website’s SEO.
How to fix it
To fix this issue, you should use the appropriate HTML elements for their intended purposes. If you need to create a hyperlink, use the
<a>
tag with a href
attribute. If you need to create a button, use the <button>
tag.
Code examples
Noncompliant code example
const MyComponent = () => {
return <>
<a href="javascript:void(0)" onClick={foo}>Perform action</a>
<a href="#" onClick={foo}>Perform action</a>
<a onClick={foo}>Perform action</a>
</>;
};
Compliant solution
const MyComponent = () => {
return <>
<button onClick={foo}>Perform action</button>
<a href="#section" onClick={foo}>Perform action</a>
</>;
};
Resources
Documentation