What does the role attribute do?
The role attribute in HTML is used to indicate an element's semantic role, that is, to tell the browser and assistive technologies (for example, screen readers) what kind of element it is and what function it performs.
It makes an interface understandable for people using screen readers, especially when a page is built not on native tags (<button>, <nav>, <header>) but on <div> and <span>.
Main idea
role exists to:
- give meaning to an element that does not have one by default;
- indicate the type of the element (button, dialog, menu, tab, table, and so on);
- make custom UI components accessible to screen readers.
A simple example
<div role="button" tabindex="0">Submit</div>For a sighted user, this is an ordinary button.
For a screen reader without role, it is just "a group of text".
With role="button", the program announces:
"Button. Submit."
When role is especially needed
- When you use non-standard elements:
<div role="checkbox" aria-checked="true">Agree</div>- When you build custom components in JS, for example tabs, dropdown lists, or modal windows.
<div role="tablist">
<div role="tab" aria-selected="true">Tab 1</div>
<div role="tab">Tab 2</div>
</div>- When you want to clarify the meaning of a native element, for example:
<section role="region" aria-label="News"></section>Commonly used role values
| Category | Example roles | Purpose |
|---|---|---|
| Structure | banner, main, navigation, contentinfo, complementary | Define the main regions of a page |
| Interactive elements | button, link, checkbox, menuitem, switch, tab, slider | Make an element operable |
| Containers / groups | list, listbox, grid, menu, tablist, toolbar | Define groups of related elements |
| Dialogs / notifications | alert, dialog, tooltip, status | Notify the user of changes |
| Table structures | table, row, cell, columnheader, rowheader | Describe data in tabular form |
Rules of use
- Use
roleonly when necessary. If a native element exists (<button>,<nav>,<header>), ARIA is not needed. -> Native semantics is always preferable. roledoes not change the visuals, only the semantics and perception. A screen reader "hears" something different, but the appearance stays the same.- Incorrect use is harmful. The wrong role confuses assistive technologies and worsens accessibility.
Example of correct code
<nav role="navigation" aria-label="Main menu">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About us</a></li>
</ul>
</nav>The screen reader announces:
"Navigation. Main menu."
Conclusion:
The role attribute tells assistive technologies the function of an element, making an interface accessible and understandable.
It is needed when:
- there is no native tag,
- you are building a custom element,
- you need to clarify the semantics.
In simple terms: HTML shows what an element looks like, and
roleexplains what it does.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.