completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

ARIA with ElementInternals

Learn ElementInternals ARIA: give a custom element a default role and states, like a switch that is on or off, with no attributes on its tag.

By the end, you can
  • 01
    Give a component default semanticsAsk for ElementInternals once, in the class, and set role and states like ariaChecked, with no attributes on the tag.
  • 02
    Keep the state trueFlip a switch's ariaChecked on a click and on Space, with a custom state for its look, and check it in Chrome's accessibility tree.
  • 03
    Let the page decideKnow that the page's role and aria-* attributes beat your defaults, and support old browsers without a polyfill.

How do you give a custom element an ARIA role?

Leaf and Kettle's order page gets a new control: Add milk. It's either on or off. So Ravi builds it as a switch, a tag called <tea-toggle>. Leela orders with a screen reader. She should hear that this is a switch, that it's called Add milk, and that it's off.

In lesson 13.1, a tag with no role got no row in Chrome's accessibility tree. So the switch needs a role and a state. Lessons 10.1 and 13.1 wrote a role attribute on the tag. But the tag belongs to the page. Can a component give itself a role without writing on its own tag?

Yes. A custom element can ask for its ElementInternals with attachInternals(). Then internals.role = "switch" and internals.ariaChecked = "false" give it a default role and state. Screen readers get them, but they never show up as attributes. And the page's own role and aria-* attributes still win.

Here is the smallest switch that does it:

A switch whose role and state live in its internalsPop out in the code editor (opens in a new tab)HTML
<tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  console.log("Attributes:", toggle.getAttributeNames().length);</script>
ResultLoading…
  • In the tea-toggle.js tab, line 2 asks for the element's internals and keeps them in #internals. The # makes the field private: only the class can reach it.
  • Line 6 gives the element a default role, switch. Line 7 gives it a default state: not checked. ARIA values are text, so "false" is in quotes.
  • On the page, line 1 is the switch, with its text. Line 5 prints how many attributes the tag has: Attributes: 0.

Chrome's accessibility tree for this page, shortened as in lesson 13.1, has one row:

Chrome's accessibility tree for the switchText
switch "Add milk", checked: false

A switch, named Add milk, and not checked. That's the role, the name, and the state a screen reader reads. The name comes from the tag's text. To see it yourself, open DevTools on the result and select the tag. The Elements panel shows no role attribute. The Accessibility tab shows the role under Computed Properties.

Compare it with the way lessons 10.1 and 13.1 did it:

The same switch with attributes on its tagPop out in the code editor (opens in a new tab)HTML
<tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  console.log("Attributes:", toggle.getAttributeNames().length);</script>
ResultLoading…

Lines 3 and 4 of this tea-toggle.js tab write role and aria-checked on the tag when it joins the page. Chrome's tree shows the same row. But the page prints Attributes: 2. The component wrote on a tag the page owns. WebKit's Ryosuke Niwa calls that surprising, "since no built-in element does this". A <button> is a button without a role attribute.

Two windows on the left. Top, titled Elements: a card <tea-toggle> and the note no role, no aria-checked. Bottom, titled internals: cards role: "switch" and ariaChecked: "false". Arrows from both go right to a window titled accessibility tree, with a card switch "Add milk" and a card checked: false, labelled what a screen reader reads.Elements<tea-toggle>no role, no aria-checkedinternalsrole: "switch"ariaChecked: "false"accessibility treeswitch "Add milk"checked: falsewhat a screen reader reads
The tag in the page has no role or aria-checked attribute. Chrome's accessibility tree takes the name from the tag's text, and the role and the state from the internals.
Real-life analogyA licence on file, or a name on the window

Leaf and Kettle's licence says what the business is: a tea shop. It's kept on file at the town office. The town's visitor guide reads that file for every shop. Ravi could also paint TEA SHOP on the window. But the window is shared with the landlord, who may paint over it, or want his own words there.

In real life: The licence kept at the town office
In HTML: this.#internals.role = "switch"
In real life: Paint on the shop window
In HTML: A role attribute on the tag
In real life: The town's visitor guide
In HTML: Chrome's accessibility tree
In real life: The window the landlord shares
In HTML: The tag, which belongs to the page
The main idea

ElementInternals gives a component default ARIA semantics. Set role and states like ariaChecked on the internals. The accessibility tree shows them, and the tag gets no attributes. The page can still override them with its own.

Why it matters: a component can be a switch, a checkbox, or a button the moment it's defined, and the page's markup stays its own.

What does attachInternals() do?

attachInternals() gives a custom element its ElementInternals: an object that holds the element's private settings. Lesson 6.2 used it to reach a closed shadow root. Lesson 12.3 used its states. This lesson uses its ARIA properties.

An element hands out its internals once, like the keys to a new shop. Every call after the first one throws. So the class asks first, in a private field: #internals = this.attachInternals();. A field runs while the element is built, right after super(). Here a page asks three elements for theirs:

Three elements that won't hand over their internalsPop out in the code editor (opens in a new tab)HTML
<tea-toggle>Add milk</tea-toggle><tea-cup>Green tea</tea-cup><div>Black tea</div><script src="tea-toggle.js"></script><script>  for (const element of document.querySelectorAll("tea-toggle, tea-cup, div")) {    try {      element.attachInternals();      console.log(element.localName, "gave its internals");    } catch (error) {      console.log(element.localName, error.name);    }  }</script>
ResultLoading…
  • Lines 1 to 3 are three tags: the switch, a <tea-cup> that nothing defines, and a div.
  • Line 4 loads the switch's class from the overview.
  • Line 6 loops over the three. Line 8 asks each one for its internals. Line 11 prints the error's name.

It prints tea-toggle NotSupportedError, tea-cup NotSupportedError, and div NotSupportedError. Chrome's messages give the reasons:

  • The switch: "ElementInternals for the specified element was already attached." Its class asked first, on line 2 of its tab.
  • The <tea-cup> and the div: "Unable to attach ElementInternals to non-custom elements." A tag that nothing defined isn't a custom element yet.

Two more cases throw too. Lesson 5.7 showed one: a customized built-in, like <button is="...">. And a class can turn its internals off with static disabledFeatures = ["internals"]. MDN lists most of these, and the HTML Standard's steps check every case in order.

Is the constructor a safe place for the defaults? Yes. Lesson 3.2 showed that a constructor must not add attributes, or createElement() fails. The internals add none. So the class can set every default as it's built. Exercise 4 shows the difference.

The internals don't need a shadow root either. The overview's switch has none. So a light DOM component, like the ones in lesson 6.4, can use them too.

One more use: attachInternals() is also how a custom element joins a form, with static formAssociated = true, form values, and validity. Forms covers that, starting with lesson 16.1.

How do internals.role and the ARIA properties work?

The internals have a role property. They also have a property for most aria-* attributes. Each name is the attribute's name without dashes, in camelCase: aria-checked becomes ariaChecked. MDN lists more than 40. These come up most:

  • role: what the element is, like "switch", "checkbox", or "button".
  • ariaChecked: on or off, for a switch or a checkbox.
  • ariaPressed: pressed or not, for a toggle button.
  • ariaExpanded: open or closed, for a button that shows and hides a panel.
  • ariaDisabled: seen, but not usable right now.
  • ariaLabel: a default name, for a control with no text.

Every value is text, as an attribute's is. Set true, and you read back "true". Set null to take a default away. Try four sets of defaults on the same tag:

Playground: which role do the internals give?
A toggle whose internals give it a default role and statePop out in the code editor (opens in a new tab)HTML
<tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script>
ResultLoading…
Chrome's accessibility tree for this page (shortened)Text
switch "Add milk", checked: false
Try it yourself
A switch that is off

The row is a switch, named by its text. ariaChecked gives it a checked state: false, so a screen reader says it's off.

The page stays the same. Only lines 6 and 7 of the tea-toggle.js tab change. The tag never gets an attribute.
  • On the page, line 1 is the tag, with its text. It never changes.
  • In the tea-toggle.js tab, line 6 sets the role and line 7 sets the state.

A checkbox uses ariaChecked, like a switch. A toggle button uses ariaPressed instead. With no defaults, Chrome ignores the tag and keeps only its text, as in lesson 13.1. Why it matters: pick the role that matches what the control does, then the state that goes with it.

Why does internals.role return null?

Reading these properties back can surprise you. Here the class reads its role before and after setting it:

Reading internals.role and the tag's rolePop out in the code editor (opens in a new tab)HTML
<tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  console.log("The tag's role:", toggle.role);</script>
ResultLoading…
  • In the tea-toggle.js tab, line 6 reads internals.role before anything is set. It prints Before: null.
  • Line 7 sets it, and line 8 prints After: switch.
  • On the page, line 5 reads the tag's own role property. It prints The tag's role: null.

internals.role gives back only what the class set. MDN says it never returns the element's implicit role, the one the browser works out by itself. The tag's role property reads the role attribute, and there isn't one. So neither tells you what a screen reader gets. The accessibility tree does.

The internals also have properties that point at other elements, like ariaLabelledByElements, ariaDescribedByElements, and ariaActiveDescendantElement. Lesson 13.3 covers them.

How do you keep an ARIA state in sync?

A default is set once, but a switch changes. Each time it flips, the class has to change ariaChecked itself. The browser never does it for you. Changing a default is fine. The HTML Standard says default semantics can change over time, the way an <a> becomes a link once it has an href.

Real-life analogyThe OPEN sign on the shop door

Every morning, Meena unlocks Leaf and Kettle's door. Then she turns the sign on the door to OPEN. The lock and the sign are separate. If she forgets the sign, people in the street think the shop is closed, though the door opens.

In real life: Unlocking the door
In HTML: The switch turning on
In real life: Turning the sign to OPEN
In HTML: Setting ariaChecked to "true"
In real life: People reading the sign from the street
In HTML: Screen readers reading the accessibility tree
In real life: An open door with a CLOSED sign
In HTML: A switch that looks on but reads as off

Here is the switch with a click, the Space key, and a look of its own:

A switch that flips on a click and on SpacePop out in the code editor (opens in a new tab)HTML
<style>  tea-toggle { display: inline-block; padding: 4px 12px; border: 2px solid gray; border-radius: 16px; }  tea-toggle:state(checked) { border-color: seagreen; background: honeydew; }</style><p>Your order</p><tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  toggle.addEventListener("click", () => console.log("Milk:", toggle.matches(":state(checked)") ? "on" : "off"));</script>
ResultLoading…
  • In the tea-toggle.js tab, lines 6 and 7 are the defaults, as before.
  • Line 8 calls #flip() on every click. The # makes it a private method.
  • Lines 9 to 13 handle Space. Line 10 ignores every other key. Line 11 stops the page from scrolling, which Space does by itself. Line 12 calls click(), so Space runs the click code, and the page hears a click too.
  • Line 17 puts the switch in the Tab order, unless the page wrote a tabindex. That writes an attribute, so it waits for connectedCallback(). The internals have no property for focus.
  • Lines 21 and 22 flip ariaChecked from "false" to "true", or back.
  • Lines 23 and 24 add or remove a custom state, checked, as in lesson 12.3. On the page, line 3 turns the switch green while it has that state.
  • On the page, line 10 prints the state after each click.

Chrome's tree before any click:

Chrome's accessibility tree for the switch pageText
paragraph
  StaticText "Your order"
switch "Add milk", checked: false
  • Click the switch. It turns green, and the page prints Milk: on. Line 3 of the tree now says checked: true.
  • Click Your order, then press Tab. Focus lands on the switch. Press Space: it prints Milk: off.
  • Press Enter. Nothing happens yet. Exercise 5 adds it.
A card click or Space, with an arrow to a function card #flip(). Two arrows leave it. The top one goes to a card ariaChecked: "true", labelled the accessibility tree hears it. The bottom one goes to a card states: checked, labelled the page's CSS sees it.click or Space#flip()ariaChecked: "true"the accessibility tree hears itstates: checkedthe page's CSS sees it
Every flip sets two things. ariaChecked tells screen readers the switch is on. The checked custom state lets CSS show it. Neither one changes the tag's attributes.

Why set both? They do different jobs. Lesson 12.3 showed that a custom state never reaches the accessibility tree. And ariaChecked isn't an attribute, so a CSS rule like [aria-checked="true"] never matches the tag.

Which keys does a switch need? The ARIA Authoring Practices Guide's switch pattern says Space flips it, and Enter may flip it too. It also says the label must not change with the state. So the name stays Add milk, and only checked changes. Chrome's guide to accessible web components builds a switch from the same parts. Module 14, in Accessible components, goes deeper into focus and keys, starting with Focus delegation and focus styles.

Does the role attribute override ElementInternals?

Yes. The HTML Standard says internals.role sets the default role, "which will be used unless the page author overrides it using the role attribute". The aria properties work the same way with aria-* attributes. Another part calls these the element's "default semantics".

Real-life analogyChai comes with milk, unless the slip says no

Leaf and Kettle's masala chai comes with milk. That's in the kitchen's recipe book. If a customer's slip says no milk, the slip wins. If the next slip says nothing, that chai comes with milk again.

In real life: The kitchen's recipe book
In HTML: The internals
In real life: The order slip
In HTML: Attributes the page writes on the tag
In real life: "No milk" on the slip
In HTML: role="checkbox" or aria-checked="true" on the tag
In real life: A slip that says nothing
In HTML: No attribute: the default is used

Try it. Here is the switch from the section before. Change what the page writes on its tag:

Playground: what does the page write on the tag?
The switch, with something the page wrote on its tagPop out in the code editor (opens in a new tab)HTML
<style>  tea-toggle { display: inline-block; padding: 4px 12px; border: 2px solid gray; border-radius: 16px; }  tea-toggle:state(checked) { border-color: seagreen; background: honeydew; }</style><p>Your order</p><tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  toggle.addEventListener("click", () => console.log("Milk:", toggle.matches(":state(checked)") ? "on" : "off"));</script>
ResultLoading…
The switch's row in Chrome's accessibility tree, before a clickText
switch "Add milk", checked: false
Try it yourself
The defaults are used

The page wrote nothing, so the internals decide. Click the switch, and the row says checked: true.

Only line 6 of the page changes. The tea-toggle.js tab is the switch from the section before, with the same defaults every time.
  • With role="checkbox", the row is a checkbox. The state still comes from the internals, so a click still ticks it.
  • With aria-label, the page's words become the name, in place of the text.
  • With aria-checked="true", the state is stuck. Click twice: the page prints Milk: on, then Milk: off. The row stays checked: true both times.

Take the page's attribute away again, and the default comes back. Remove role with removeAttribute(), and Chrome's row is a switch again.

Two halves. Left, labelled the page wrote nothing: a card <tea-toggle> over a card internals: switch, with an arrow down to switch "Add milk". Right, labelled the page wrote a role: a card <tea-toggle role="checkbox"> over a faded, crossed-out card internals: switch, with an arrow down to checkbox "Add milk".The page wrote nothing<tea-toggle>internals: switchswitch "Add milk"The page wrote a role<tea-toggle role="checkbox">internals: switchcheckbox "Add milk"
The internals give a default. When the page writes its own role on the tag, Chrome uses the page's role, and the default waits until that attribute is gone.

Should a page write a role over yours, then? ARIA in HTML says no: when the internals give a role, the page shouldn't add one. The HTML Standard's own example calls such markup "probably not what the custom element author intended". So write your defaults down in your docs, and treat a page's attribute as the page's choice.

And the component must never overwrite the page's attributes. With internals, it can't by accident. The old way needed a hasAttribute() check before every write, as lesson 10.1's tabs and web.dev's checklist do.

Do you need the ElementInternals polyfill?

Not for today's browsers. internals.role works in Chrome 103, Firefox 119, and Safari 16.4 and later, by MDN's browser-compat-data. The states, like ariaChecked, came earlier in Chrome, in version 81. web-features groups them as ARIA attribute reflection, Baseline widely available. You may read that Safari doesn't support ElementInternals. That was true before Safari 16.4.

element-internals-polyfill filled the gap for older browsers. It checks for ElementInternals and its form features. When they're missing, it adds its own. Its ARIA properties write attributes: set ariaChecked to "true", and its README says the tag gets aria-checked="true". So in an old browser, it does the old way for you. In today's browsers, it finds ElementInternals and does nothing.

The polyfill only checks the form features, though. Firefox 98 to 118 had those, but no ARIA properties on the internals. So the polyfill stepped aside there, and internals.role = "switch" only stored a value on the object. Why it matters: to support a browser like that, check for role itself.

Real-life analogyPaper signs while the town office is shut

One summer, the town office closes for repairs, and the visitor guide can't read its files. So each shop tapes a paper sign in its window saying what it is. Visitors still find the tea shop. When the office opens again, the paper signs come down.

In real life: The town office and its files
In HTML: The browser's own ElementInternals
In real life: A town where the office is shut
In HTML: An old browser without it
In real life: A paper sign taped to the window
In HTML: An attribute the polyfill or a fallback writes
In real life: Taking the paper signs down
In HTML: Today's browsers, which need none of it

If some of your visitors use a very old browser, you don't need a whole polyfill for a role. Check whether the internals have role, and fall back to lesson 10.1's way. Switch between the two browsers:

Playground: today's browser or an old one?
A toggle that falls back to a role attributePop out in the code editor (opens in a new tab)HTML
<script src="browser.js"></script><tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  console.log("role attribute:", toggle.getAttribute("role"));</script>
ResultLoading…
Chrome's accessibility tree for this page (shortened)Text
switch "Add milk", checked: false
Try it yourself
The role comes from the internals

The browser has internals.role, so line 8 of the tea-toggle.js tab sets it. The tag gets no attribute, and the page prints role attribute: null.

The page and the tea-toggle.js tab stay the same. Only the browser.js tab changes: the old browser is Chrome with ElementInternals.role removed.
  • In the tea-toggle.js tab, line 1 checks once whether ElementInternals has a role. The ?. and ?? stop it from throwing in a browser with no ElementInternals at all.
  • Line 4 asks for the internals, but only if attachInternals() exists.
  • Line 8 uses the internals when it can.
  • Line 12 is the old way: a role attribute when the tag joins the page, and only if the page wrote none.

Today's browser prints role attribute: null. The old one prints role attribute: switch. The tree is the same either way. Why it matters: the fallback takes a few lines, and the page's own role wins in both.

Adding a switch to the tea kit

The kit gets its first switch, tea-toggle, for choices like Add milk. It's the switch from this lesson, with the kit's styles. Open the tea-kit/tea-toggle.js tab to read it.

Two kit switches on an order pagePop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Your order</p><tea-toggle>Add milk</tea-toggle><tea-toggle checked>Add honey</tea-toggle><script type="module" src="tea-kit/index.js"></script><script type="module">  for (const toggle of document.querySelectorAll("tea-toggle")) {    toggle.addEventListener("click", () => console.log(toggle.textContent + ":", toggle.checked ? "on" : "off"));  }</script>
ResultLoading…
  • On the page, line 3 is a switch that starts off. Line 4 starts on, with the checked attribute.
  • Lines 7 to 9 print each switch's state after a click.
  • In the tea-kit/tea-toggle.js tab, line 35 asks for the internals. Lines 39 and 40 set the defaults.
  • Lines 44 to 51 flip the switch on a click, and turn Space into a click. Line 55 adds the tab stop.
  • Lines 58 to 60 let the checked attribute turn the switch on or off. Lines 67 to 72 write both ariaChecked and the checked state. The switch never writes the checked attribute itself.
Chrome's accessibility tree for the two kit switchesText
paragraph
  StaticText "Your order"
switch "Add milk", checked: false
switch "Add honey", checked: true

Click Your order and press Tab: focus lands on Add milk. Press Space, and the page prints Add milk: on. The only attribute the switch adds is tabindex, since focus has no internals property. The JSDoc and custom-elements.json document the tag, its checked attribute and property, its slot, its track part, and its checked state. The JSDoc also says the tag is a switch by default, and that a role the page writes wins, so page authors know the defaults.

The tabs move their role into the internals

Lesson 10.1 gave the tabs' tag role="presentation" in connectedCallback(), unless the page wrote a role. That role tells screen readers to skip the wrapper. Now the tabs set it in their internals. These are the changed lines in tea-kit/tea-tabs.js:

The tabs' default role, now in their internalsJavaScript
  #internals = this.attachInternals();

  constructor() {
    super();
    this.#internals.role = "presentation";

Line 1 asks for the internals. Line 5 sets the default role in the constructor. The old line in connectedCallback() is gone. Here are the kit's tabs now:

The kit's tabs with their role in the internalsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-tabs label="Brewing guide"><button slot="tab">Green</button><button slot="tab">Oolong</button><p slot="panel">Brew for 3 minutes.</p><p slot="panel">Brew for 4 minutes.</p></tea-tabs><script type="module" src="tea-kit/index.js"></script><script type="module">  console.log("role attribute:", document.querySelector("tea-tabs").getAttribute("role"));</script>
ResultLoading…
Chrome's accessibility tree for the tabs, before and afterText
tablist "Brewing guide"
  tab "Green"
  tab "Oolong"
tabpanel "Green"

With lesson 13.1's kit, line 5 printed role attribute: presentation. Now it prints role attribute: null. Chrome's whole tree is exactly the same, ignored rows included. A page's own role, like region, still wins. This version of the kit is kitAfter132.

One quick check before the mix-ups. Where does each one belong?

Internals or an attribute?
  • The switch's default role
  • Whether the switch is on, for screen readers
  • Whether the switch is on, for CSS
  • The switch's place in the Tab order
  • Another role the page wants, like checkbox
  • A name the page wants, like Milk, please
Try it yourself
0 of 6 correct

Sort each one: does the component set it in its internals, or is it an attribute on the tag?

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "internals.role writes a role attribute." No. The tag gets no attribute, and getAttribute("role") stays null. Only the accessibility tree shows it.
  • "internals.role tells you an element's role." No. It gives back only what the class set. A fresh one reads null.
  • "The internals beat the page's attributes." No. The page's role and aria-* attributes win. The internals are only defaults.
  • "A checked custom state tells screen readers the switch is on." No. States are for CSS. ariaChecked is what the tree reads.
  • "role="switch" makes the keys work." No. A role says what the element is. The tab stop and Space are your code.
  • "You can call attachInternals() whenever you need it." No. Each element hands them out once. Ask first, in the class.
  • "Safari needs a polyfill for ElementInternals." No. Safari has had it, ARIA properties included, since Safari 16.4.

Read each row across: the same question, for a role attribute and for a default role.

A role attribute or a default role?
Questionthis.setAttribute("role", "switch")this.#internals.role = "switch"
Does the tag get an attribute?Yes. role="switch" shows in the Elements panel, where any script can change it.No. getAttributeNames() stays empty.
Can it run in the constructor?No. createElement() reports a NotSupportedError and makes a plain element instead.Yes. It adds no attribute, so the constructor rules allow it.
What if the page writes its own role?Yours wins if you write it later, unless you check hasAttribute() first.The page's role wins. Yours is only the default.
What if the page then removes its role?Nothing comes back: the tag has no role and no row.Your default comes back: the tag is a switch again.
Which browsers support it?Every browser.Chrome 103, Firefox 119, and Safari 16.4 and later.

Practice exercises

Answer first, then use the hints. The pages run live. To check a tree, open DevTools on the result and look at the Accessibility tab.

Exercise 1 · Warm-upPredict what the attribute says

Line 5 clicks the switch. What does line 6 print?

<tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  toggle.click();  console.log(toggle.getAttribute("aria-checked"));</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict the role

    What role does Chrome's accessibility tree give this tag?

    <tea-toggle role="button">Add milk</tea-toggle><script src="tea-toggle.js"></script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeGive the star a pressed state

      The star already has a tab stop and keys, but no role or state. Fill in the tea-star.js tab. Then click the star once. What does Chrome's tree say about pressed?

      <p>Oolong</p><tea-star>Favourite</tea-star><script src="tea-star.js"></script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeMake createElement() work

        The page prints HTMLUnknownElement, and the console shows a NotSupportedError. Fix line 6 of the tea-toggle.js tab. What does the page print then?

        <p>Your order</p><script src="tea-toggle.js"></script><script>  const toggle = document.createElement("tea-toggle");  toggle.textContent = "Add milk";  document.body.append(toggle);  console.log(toggle.constructor.name);</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeLet Enter flip the switch

          The APG says Enter may flip a switch too. Add it. Then click Your order, press Tab, and press Enter. What does it print?

          <style>  tea-toggle { display: inline-block; padding: 4px 12px; border: 2px solid gray; border-radius: 16px; }  tea-toggle:state(checked) { border-color: seagreen; background: honeydew; }</style><p>Your order</p><tea-toggle>Add milk</tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  toggle.addEventListener("click", () => console.log("Milk:", toggle.matches(":state(checked)") ? "on" : "off"));</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeStop overwriting the page's name

            This switch has no text, so it needs a default name. But it wipes out the page's Oat milk, and the page prints Label: Milk. Fix the tea-toggle.js tab. What does the page print then?

            <tea-toggle aria-label="Oat milk"></tea-toggle><script src="tea-toggle.js"></script><script>  const toggle = document.querySelector("tea-toggle");  console.log("Label:", toggle.getAttribute("aria-label"));</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: what did the class set in its internals, and what did the page write on the tag?

              The ARIA with ElementInternals quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-toggle>Add milk</tea-toggle>
                <script>
                  customElements.define("tea-toggle", class extends HTMLElement {
                    #internals = this.attachInternals();
                    constructor() {
                      super();
                      this.#internals.role = "switch";
                    }
                  });
                  console.log(document.querySelector("tea-toggle").getAttribute("role"));
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 8A class reads this.#internals.role before it sets anything. What does it get?

                Choose an answer to see the explanation.

              3. Question 3 of 8In Chrome's accessibility tree, what state does this switch have?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-toggle aria-checked="true">Add milk</tea-toggle>
                <script>
                  customElements.define("tea-toggle", class extends HTMLElement {
                    #internals = this.attachInternals();
                    constructor() {
                      super();
                      this.#internals.role = "switch";
                      this.#internals.ariaChecked = "false";
                    }
                  });
                </script>

                Choose an answer to see the explanation.

              4. Question 4 of 8A page calls attachInternals() on a switch whose class already asked for them. What happens?

                Choose an answer to see the explanation.

              5. Question 5 of 8Where does a switch get its place in the Tab order?

                Choose an answer to see the explanation.

              6. Question 6 of 8A switch adds a checked custom state when it's on. Is that enough for screen readers?

                Choose an answer to see the explanation.

              7. Question 7 of 8Which key must a switch handle, by the ARIA Authoring Practices Guide?

                Choose an answer to see the explanation.

              8. Question 8 of 8Do today's browsers need element-internals-polyfill for internals.role?

                Choose an answer to see the explanation.

              Key takeaways

              • attachInternals() gives a custom element its ElementInternals, once. Ask first, in a private field.
              • internals.role and properties like ariaChecked give default semantics. The tree shows them, and the tag gets no attributes.
              • internals.role reads back only what you set. Check the accessibility tree to see what a screen reader gets.
              • Flip the state yourself on every change. A custom state is for CSS. ariaChecked is for screen readers.
              • A switch needs a tab stop, set in connectedCallback(), and Space. Enter is optional.
              • The page's role and aria-* attributes beat your defaults. Never overwrite them.
              • Today's browsers don't need the polyfill. For very old ones, fall back to a role attribute the page didn't write.

              Remember the one-liner.
              Internals give a component default roles and states, with no attributes on the tag, and the page's attributes still win.

              Sources

              The facts on this page come from these standards, docs, and posts:

              Coming next: ARIA references across shadow roots. An aria-labelledby id can't cross a shadow root, and element references can.

              CompleteFrontend Clear concepts. Working examples.