Can I change the role of a custom element?

posted on

Back to overview

Yes.

You can change the generic role of a custom element just like you would with any other element.

class TheNav extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: "open" })

    this.shadow.innerHTML = `
    <ul>
      <li>
        <a href="#">Home</a>
      </li>
    </ul>
    `
  }

}

customElements.define("the-nav", TheNav)
<the-nav role="navigation" aria-label="Main"></the-nav>

You can also set the role in JavaScript.

class TheNav extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: "open" })

    this.shadow.innerHTML = `
    <ul>
      <li>
        <a href="#">Home</a>
      </li>
    </ul>
    `
  }

  connectedCallback() {
    this.setAttribute('role', 'navigation')
    this.setAttribute('aria-label', 'Main')
  }

}

customElements.define("the-nav", TheNav)

Is that a good idea? Probably not, but it’s possible.

Back to overview