Building a tabs component
Build a tabs web component step by step: scaffold the class, write its shadow markup, slot tabs and panels, wire ARIA ids, and plan its public API.
- 01Scaffold a component safelyMake the template once, attach the shadow root in the constructor, and give the host a default
roleinconnectedCallback(), only when the page hasn't. - 02Slot and connect tabs and panelsGive many children one named slot, and wire the ARIA roles,
aria-controls, andaria-labelledbywith ids in one tree. - 03Plan and build a public APISketch the API first, then add a
selectedattribute and aselectedIndexproperty that reflects it.
How do you build a tabs web component?
Asha is writing a brewing guide for the Leaf and Kettle website. Green tea, black tea, and oolong each get their own steps. Stacked one after another, the page is long, and readers scroll past the tea they want. So she asks Ravi for tabs: one button per tea, and one panel of steps showing at a time.
Ravi wants the tabs in his tea kit, so every page can use them. But tabs have many parts. Where do the buttons go? Where do the steps go? And which parts belong to the component?
A tabs web component is a custom element whose shadow root holds the tab row and the panel area. The page writes its own tabs and panels, and they arrive through two named slots. The component then links each tab to its panel with ARIA roles and ids.
ARIA is a set of attributes, like role, that tell screen readers what each element is and how elements belong together. This lesson builds that component, <tea-tabs>, step by step. Here is where it ends up. The class is in the tea-tabs.js tab:
<tea-tabs> <button slot="tab">Green</button> <button slot="tab">Black</button> <button slot="tab">Oolong</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section> <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module" src="tea-tabs.js"></script>- Lines 2 to 4 are the tabs: three buttons, each with
slot="tab". - Lines 5 to 7 are the panels: three sections, each with
slot="panel". - Line 10 loads the class. The
attribute-types.jstab is the kit's helper from lesson 5.2.
The result shows Green in bold, and only Green's steps. Now click Black. Nothing happens yet. In this lesson, only the page's own code can change the tab. The next lesson adds clicks and the arrow keys.
Look at who owns what. The page writes the buttons and the sections. They stay in the page's own tree, the light DOM. The component owns the tab row, the panel area, and the styles, in its shadow root.
Leaf and Kettle keeps its tea menu in a ring binder. Each tea has a divider with a tab, and a page of steps behind it. Asha writes the dividers and the pages. The binder only holds them in order, and one page lies open at a time. A new tea needs a new divider and a new page, not a new binder.
- In real life: The tab on each divider
- In JavaScript: The page's
<button slot="tab"> - In real life: The page of steps behind it
- In JavaScript: The page's
<section slot="panel"> - In real life: The binder and its rings
- In JavaScript:
<tea-tabs>and its shadow root - In real life: The page lying open
- In JavaScript: The selected panel
The shadow root is the frame. The page's tabs and panels are the content. The frame holds the tab row, the panel area, and the styles. The content comes in through named slots, and stays in the page's tree, where tab and panel ids can point at each other.
First comes a sketch of the API. Then the build takes five steps:
- Scaffold the class: a template, a shadow root, and a role for the host.
- Give the shadow root its own markup: the tab row and the panel area.
- Add a named slot for the tabs and one for the panels.
- Link each tab to its panel with ARIA roles and ids.
- Add the
selectedattribute and theselectedIndexproperty.
What API should a tabs component have?
Before writing code, Ravi sketches the outside of the tabs on a card. Lesson 5.4 called this the component's API: every part a page can use. Changing it later can break pages, so now is the cheapest time to get it right.
A page needs two things from tabs. They show the tea it asks for, and they tell it when the reader picks another. Read each row as a promise to every page that uses the tabs:
| Part of the API | Its name | What it does |
|---|---|---|
| Attribute | selected | Says which tab is selected, counting from 0. A page writes it in HTML, like <tea-tabs selected="1">. |
| Property | selectedIndex | Gives the same number to JavaScript. It reads and writes the selected attribute. |
| Event | tea-change | Tells the page the reader picked another tab. Lesson 10.2 sends it. It won't fire when the page sets selected itself. |
| Slot | tab | Holds every tab, in order. A <button> makes a good tab. |
| Slot | panel | Holds one panel for each tab, in the same order. |
| CSS parts and custom properties | None yet | Stage 4 adds a styling API. Each public part is a promise, so the card starts small. |
selectedIndexcopies a name the browser already uses. A<select>has a selectedIndex property too, counting from 0. Someone who knows one can guess the other.- The event follows lesson 5.3's naming rules: lowercase, the kit's
tea-prefix, and a plain word for what happened. - It fires only for the reader's own picks. web.dev's checklist says not to fire events when the page sets a property. The page already knows.
- There are two slots, because tabs and panels go to different places. A
slotattribute names the place.
Ravi orders a shelf for the shop. Before any wood is cut, the carpenter draws it on a card: how wide, how many shelves, where the hooks go. Ravi checks it against his tins. Moving a hook on the card costs nothing. Moving it after the cut costs a new board.
- In real life: The drawing on the card
- In JavaScript: The API card above
- In real life: Ravi checking it against his tins
- In JavaScript: Thinking about the pages that will use the tabs
- In real life: Cutting the wood
- In JavaScript: Writing the class
- In real life: Moving a hook after the cut
- In JavaScript: A breaking change, from lesson 5.4
How do you scaffold a web component?
Step 1 is the frame every shadow DOM component in the kit starts with. It has four parts:
- a template, made once when the file first runs (lesson 7.1);
- a class that extends
HTMLElement; - a constructor that attaches the shadow root and fills it from the template;
customElements.define(), which registers the tag.
Here is tea-tabs.js after step 1. The highlighted lines are about the host, the <tea-tabs> element itself:
const template = document.createElement("template");template.innerHTML = ` <style> :host { display: block; } :host([hidden]) { display: none; } </style> <p>The tabs go here.</p>`; export class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.append(template.content.cloneNode(true)); } connectedCallback() { if (!this.hasAttribute("role")) this.setAttribute("role", "presentation"); }} customElements.define("tea-tabs", TeaTabs);- Lines 1 to 7 make one template for every copy of the tabs. For now, it holds a placeholder.
- Line 4 makes the host a block, so it takes the full width.
:hostis a selector you write inside a shadow root. It matches the host. A custom element is inline unless you say so, web.dev notes. - Line 5 hides the host while it has the
hiddenattribute. Further down, a playground shows why. - Lines 10 to 14 are the constructor. It attaches an open shadow root and clones the template into it.
- Line 17 gives the host
role="presentation", but only if the page didn't write a role. - Line 21 registers the class as
tea-tabs.
Why presentation? The host is only a wrapper around the tab row and the panels. This role tells screen readers to skip the wrapper and read what's inside. GitHub's tab-container element gives its host the same role.
Now a page with two of them. The second brings its own role:
<tea-tabs></tea-tabs><tea-tabs role="region" aria-label="Brewing guide"></tea-tabs> <script type="module"> import "./tea-tabs.js"; for (const tabs of document.querySelectorAll("tea-tabs")) { console.log(tabs.getAttribute("role")); }</script>- Line 1 has no role. Line 2 is a region: a landmark that screen reader users can jump to, named Brewing guide.
- Line 5 loads the class. Lines 6 to 8 print each element's role.
The console prints presentation, then region. The page chose a role for the second one, and the component kept it. web.dev's checklist says the same about role and tabindex: check first, and never overwrite what the page set.
Why does the role wait for connectedCallback?
Setting the role in the constructor looks simpler. It's one line, and it runs first. Try it both ways:
<tea-tabs></tea-tabs> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.setAttribute("role", "presentation"); } connectedCallback() { // Nothing here. } } customElements.define("tea-tabs", TeaTabs); const fromHtml = document.querySelector("tea-tabs"); console.log("From HTML:", fromHtml.getAttribute("role")); const made = document.createElement("tea-tabs"); console.log("Made:", made.constructor.name, made.getAttribute("role")); document.body.append(made); console.log("Added:", made.getAttribute("role"));</script>The tag on line 1 was already on the page, so its upgrade works. But createElement() checks that a new element has no attributes. This one has a role, so Chrome reports a NotSupportedError and gives back a plain HTMLUnknownElement. It never becomes tabs.
Both versions print From HTML: presentation. So a quick test page looks fine. The difference shows up with document.createElement().
The HTML Standard says a constructor must not give the element attributes or children. Code that calls createElement() expects an empty element back. So createElement() checks. With the role in the constructor, Chrome reports a NotSupportedError. It gives back a plain HTMLUnknownElement instead of tabs. Lesson 3.2 showed this check in full.
createElement() runs only the constructor, then checks that the element came back with no attributes. The role waits for connectedCallback(), which runs when the element joins the page.Ravi orders a door for the back room. The workshop fits the hinges and the lock before it leaves. Nobody paints a name on it, because every buyer expects a blank door. The fitter hangs it, then adds a Staff only sign, unless Ravi has already put up his own.
- In real life: Fitting the hinges in the workshop
- In JavaScript: Attaching the shadow root in the constructor
- In real life: A door with nothing painted on it
- In JavaScript:
createElement()gives an element with no attributes - In real life: Hanging the door in the shop
- In JavaScript: The element joins the page:
connectedCallback() - In real life: Ravi's own sign stays up
- In JavaScript:
hasAttribute("role")keeps the page's role
connectedCallback() can run more than once, for example when the page moves the element. Line 17 is safe to run again: the second time, the role is already there. Stage 5 shows another way, ElementInternals.role, a default role with no attribute at all, in Chrome 103, Firefox 119, and Safari 16.4 and later.
Why does :host need a rule for hidden?
Line 5 of step 1 looks odd. The hidden attribute already hides things, doesn't it? Turn the rule off and see:
<tea-tabs hidden>Green, Black, Oolong</tea-tabs><p>The rest of the page.</p> <script> const template = document.createElement("template"); template.innerHTML = ` <style> :host { display: block; border: 2px solid seagreen; } /* No rule for hidden. */ </style> <slot></slot>`; class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.append(template.content.cloneNode(true)); } } customElements.define("tea-tabs", TeaTabs); const tabs = document.querySelector("tea-tabs"); console.log("display:", getComputedStyle(tabs).display);</script>The tag has hidden, but the tabs still show, with their green border. The browser's own rule for hidden says display: none. Line 8 is your rule, and a rule you write beats a built-in one.
Without line 9, the tabs ignore hidden, and the console prints display: block. Here's why. hidden works through one rule in the browser's own stylesheet, display: none. The HTML Standard lists it. Line 8 is your rule, and a rule you write beats a built-in one.
Line 9 matches the host only while it has hidden. It's more specific than :host alone, so it wins over line 8. That's the pair web.dev's checklist asks for. Lesson 11.2, Styling the host, looks at :host in depth.
Now sort the jobs. Where does each one belong?
this.attachShadow({ mode: "open" })- Cloning the template into the shadow root
- Listening for
slotchangeon the two slots - Giving the host
role="presentation" - The first
#render(), when the tabs join the page - Drawing again when
selectedchanges
Sort each job by where the tabs do it.
What goes in the tabs component's shadow root?
Step 2 gives the shadow root the component's own markup: the parts it draws, whatever the page puts inside. For tabs, that's a row for the tabs, an area for the panel, and their styles. Only the template changes:
const template = document.createElement("template");template.innerHTML = ` <style> :host { display: block; } :host([hidden]) { display: none; } .tabs { display: flex; gap: 4px; border-bottom: 2px solid seagreen; } .panels { padding: 8px 0; } </style> <div class="tabs" role="tablist">Tab row</div> <div class="panels">Panel area</div>`;- Line 6 lays the tab row out in a line, with a small gap and a green line under it.
- Line 7 gives the panel area some room above and below.
- Line 9 is the tab row. It gets
role="tablist". - Line 10 is the panel area.
<tea-tabs></tea-tabs> <script type="module"> import "./tea-tabs.js"; const tabs = document.querySelector("tea-tabs"); const row = tabs.shadowRoot.querySelector(".tabs"); console.log("Row:", row.getAttribute("role")); console.log("Host:", tabs.getAttribute("role"));</script>The result shows Tab row over a green line, and Panel area under it. Line 6 finds the row inside the shadow root. The console prints Row: tablist and Host: presentation.
Why does the row get role="tablist", and not the host? The ARIA standard describes a tab list as a list of tabs, and tabs are the only children it allows. The panels are separate, next to it. The host holds the tab row and the panel area. As a tab list, it would hold the panels too.
Before tea-tabs.js loads, the browser doesn't know the tag. It shows the page's buttons and sections one after another, so the steps are still there to read. Heydon Pickering's chapter on tabbed interfaces starts the same way: plain content first, tabs on top.
Can many elements share one named slot?
Yes. Every child with the same slot name goes into the same slot. MDN puts it plainly: the slot attribute doesn't need to be unique, and one slot can be filled by many elements. That's what tabs need: one slot for every tab, and one for every panel.
Step 3 swaps the placeholder text for two named slots:
const template = document.createElement("template");template.innerHTML = ` <style> :host { display: block; } :host([hidden]) { display: none; } .tabs { display: flex; gap: 4px; border-bottom: 2px solid seagreen; } .panels { padding: 8px 0; } </style> <div class="tabs" role="tablist"><slot name="tab"></slot></div> <div class="panels"><slot name="panel"></slot></div>`;Line 9 puts <slot name="tab"> in the tab row. Line 10 puts <slot name="panel"> in the panel area. Lesson 8.1 built named slots like these.
<tea-tabs> <button slot="tab">Green</button> <button slot="tab">Black</button> <button slot="tab">Oolong</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section> <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const tabs = document.querySelector("tea-tabs"); for (const slot of tabs.shadowRoot.querySelectorAll("slot")) { const names = slot.assignedElements().map((element) => element.localName); console.log(slot.name + ":", names.join(", ")); }</script>- Lines 2 to 4 are three buttons with
slot="tab". Lines 5 to 7 are three sections withslot="panel". - Line 13 loops over the two slots in the shadow root.
- Line 14 asks each slot for its assigned elements, as in lesson 8.3, and keeps their tag names.
- Line 15 prints each slot's name and what it holds.
The console prints tab: button, button, button and panel: section, section, section. Each slot holds all three, in page order. The buttons sit in a row above the green line. All three sections show under it, for now. Step 4 hides two of them.
The tea shop's back room has a pigeonhole for each member of staff. Every letter for Ravi goes in Ravi's, however many arrive. They stack up in the order the post came. Nobody adds a second pigeonhole for his second letter.
- In real life: The pigeonhole marked Ravi
- In JavaScript:
<slot name="tab"> - In real life: The name on each envelope
- In JavaScript:
slot="tab"on each button - In real life: Letters stacked as the post came
- In JavaScript: The tabs, in page order
- In real life: A letter with a misspelt name
- In JavaScript: A child whose slot name matches no slot, which doesn't show
Why not manual slot assignment, from lesson 8.5? It suits components that sort children by kind or position, with no slot attributes. Here the page already says which child is a tab. MDN calls named slots the most suitable method for most use cases. And the markup reads clearly: slot="tab" says what each child is.
How do tabs and panels point at each other?
A screen reader can't see that Green's steps sit under the Green button. The APG, the ARIA Authoring Practices Guide, says how to tell it, with ARIA attributes:
- the element around the tabs has
role="tablist", which step 2 did; - each tab has
role="tab", andaria-selectedset to"true"or"false"; - each tab's
aria-controlsholds the id of its panel; - each panel has
role="tabpanel", andaria-labelledbyholding the id of its tab.
Pointing by id needs ids. The page may not give any, so the component makes them up. Step 4 adds a private method, #render(), that does all of this. It shows only the first panel:
const template = document.createElement("template");template.innerHTML = ` <style> :host { display: block; } :host([hidden]) { display: none; } .tabs { display: flex; gap: 4px; border-bottom: 2px solid seagreen; } .panels { padding: 8px 0; } ::slotted([aria-selected="true"]) { font-weight: bold; } </style> <div class="tabs" role="tablist"><slot name="tab"></slot></div> <div class="panels"><slot name="panel"></slot></div>`; let nextId = 1; export class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.append(template.content.cloneNode(true)); for (const slot of this.shadowRoot.querySelectorAll("slot")) { slot.addEventListener("slotchange", () => this.#render()); } } connectedCallback() { if (!this.hasAttribute("role")) this.setAttribute("role", "presentation"); this.#render(); } #render() { const [tabSlot, panelSlot] = this.shadowRoot.querySelectorAll("slot"); const panels = panelSlot.assignedElements(); tabSlot.assignedElements().forEach((tab, index) => { const panel = panels[index]; if (!panel) return; const selected = index === 0; if (!tab.id) tab.id = `tea-tab-${nextId++}`; if (!panel.id) panel.id = `${tab.id}-panel`; tab.setAttribute("role", "tab"); tab.setAttribute("aria-selected", String(selected)); tab.setAttribute("aria-controls", panel.id); panel.setAttribute("role", "tabpanel"); panel.setAttribute("aria-labelledby", tab.id); panel.hidden = !selected; }); }} customElements.define("tea-tabs", TeaTabs);- Line 8 makes the selected tab bold. ::slotted() styles the page's elements that sit in a slot. Stage 4 covers it.
- Line 13 is a counter for made-up ids. It sits outside the class, so every tabs element on the page shares it.
- Lines 20 to 22 run
#render()again whenever the page adds or removes a tab or a panel, with the slotchange event from lesson 8.4. So a tab added later gets set up too. - Line 27 draws the tabs as soon as they're on the page.
- Lines 31 to 34 get the tabs and the panels from the two slots. Tab 0 pairs with panel 0, tab 1 with panel 1.
- Line 35 leaves a tab with no panel alone.
- Line 36 picks the first tab. Step 5 turns this into a choice.
- Lines 37 and 38 give the tab an id if it has none, and the panel its tab's id plus
-panel. - Lines 39 to 41 set the tab's role, its
aria-selected, and the panel it controls. - Lines 42 to 44 set the panel's role and the tab that names it. Every panel but the selected one gets
hidden.
<tea-tabs> <button slot="tab" id="green">Green</button> <button slot="tab">Black</button> <button slot="tab">Oolong</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section> <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; for (const tab of document.querySelectorAll('[role="tab"]')) { console.log(tab.id, "controls", tab.getAttribute("aria-controls")); }</script>Line 2 gives Green its own id, green. Lines 12 to 14 print each tab's id and the panel it controls. The console prints green controls green-panel, tea-tab-1 controls tea-tab-1-panel, and tea-tab-2 controls tea-tab-2-panel. The page's id stays. The other two come from the counter.
aria-controls names the panel's id, and the panel's aria-labelledby names the tab's id. Both lookups happen in the page's tree, so both find their element.Chrome's accessibility tree shows the result. It has a tab list with three tabs: Green, selected, then Black and Oolong. Next to it is one tab panel, named Green, after its tab. The hidden panels aren't in the tree at all. Heydon Pickering explains the name: a screen reader user who moves into the panel hears which tab it belongs to.
The tab list still has no name of its own. The APG asks for one, like Brewing guide. Exercise 6 adds it.
Does aria-controls work across shadow DOM?
No. That's why the panels stay in the page, next to the tabs. Here a teammate keeps the tab in the page but builds the panel inside the shadow root:
<tea-tabs> <button slot="tab" role="tab" aria-controls="green-panel">Green</button></tea-tabs> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <div role="tablist"><slot name="tab"></slot></div> <section id="green-panel" role="tabpanel">Steep green tea for 2 minutes.</section>`; } } customElements.define("tea-tabs", TeaTabs); const tab = document.querySelector("button"); console.log("Found:", tab.ariaControlsElements.length);</script>- Line 2 is the page's tab. Its
aria-controlsnamesgreen-panel. - Line 12 is the panel with that id, inside the shadow root.
- Line 18 asks the tab which elements its
aria-controlsfound. ARIA attributes that hold ids have matching properties, like this one, ariaControlsElements.
The console prints Found: 0. The tab looked for green-panel in its own tree, the page's, and the panel isn't there. MDN gives the rule: an id reference can only point at elements in the same DOM or the same shadow DOM. Lesson 6.3 showed ids stay inside their own tree. This is the other side of it.
At a concert, you leave your coat at the cloakroom and get ticket 42. Ticket 42 finds your coat at that counter. The theatre next door has its own cloakroom and its own numbers. Your ticket means nothing there.
- In real life: The number on your ticket
- In JavaScript: The id in
aria-controls - In real life: The coats on this cloakroom's rail
- In JavaScript: The elements in the page's tree
- In real life: The cloakroom next door
- In JavaScript: A shadow root
- In real life: Showing your ticket at the counter
- In JavaScript: The browser looking up the id
A newer feature, Reference Target, lets an id that points at a host reach one chosen element inside its shadow root. Only Chrome has it, from Chrome 152. Stage 5, Accessible components, covers it. Keeping both ends in the page works in every browser.
Adding the selected attribute and selectedIndex property
Step 5 builds the rest of the API card: the selected attribute and the selectedIndex property. Here is the finished tea-tabs.js:
import { toNonNegativeInteger } from "./attribute-types.js"; const template = document.createElement("template");template.innerHTML = ` <style> :host { display: block; } :host([hidden]) { display: none; } .tabs { display: flex; gap: 4px; border-bottom: 2px solid seagreen; } .panels { padding: 8px 0; } ::slotted([aria-selected="true"]) { font-weight: bold; } </style> <div class="tabs" role="tablist"><slot name="tab"></slot></div> <div class="panels"><slot name="panel"></slot></div>`; let nextId = 1; /** * Tabs: the page's tabs in a row, and the selected tab's panel under them. * * @tag tea-tabs * @attr {number} selected - Which tab is selected, counting from 0. A missing or bad value means 0. * @slot tab - The tabs, such as buttons, in order. * @slot panel - One panel for each tab, in the same order. */export class TeaTabs extends HTMLElement { static observedAttributes = ["selected"]; constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.append(template.content.cloneNode(true)); for (const slot of this.shadowRoot.querySelectorAll("slot")) { slot.addEventListener("slotchange", () => this.#render()); } } connectedCallback() { if (!this.hasAttribute("role")) this.setAttribute("role", "presentation"); this.#render(); } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; this.#render(); } /** Which tab is selected, counting from 0. Reflects the selected attribute. */ get selectedIndex() { return toNonNegativeInteger(this.getAttribute("selected"), 0); } set selectedIndex(value) { this.setAttribute("selected", value); } #render() { const [tabSlot, panelSlot] = this.shadowRoot.querySelectorAll("slot"); const panels = panelSlot.assignedElements(); tabSlot.assignedElements().forEach((tab, index) => { const panel = panels[index]; if (!panel) return; const selected = index === this.selectedIndex; if (!tab.id) tab.id = `tea-tab-${nextId++}`; if (!panel.id) panel.id = `${tab.id}-panel`; tab.setAttribute("role", "tab"); tab.setAttribute("aria-selected", String(selected)); tab.setAttribute("aria-controls", panel.id); panel.setAttribute("role", "tabpanel"); panel.setAttribute("aria-labelledby", tab.id); panel.hidden = !selected; }); }} customElements.define("tea-tabs", TeaTabs);- Line 1 imports
toNonNegativeInteger(), the kit's reader for whole numbers from lesson 5.2. - Lines 17 to 24 write the API card down as JSDoc comments, so tools can read it (lesson 5.4).
- Line 26 asks the browser to watch the
selectedattribute, as in lesson 3.4. - Lines 42 to 45 draw again when it changes. Line 43 skips a write of the same value, as the kit's card has done since lesson 7.3.
- Lines 48 to 50 are the getter. It reads the attribute as a whole number. A missing or bad value means 0, the first tab.
- Lines 52 to 54 are the setter. It only writes the attribute, so the number lives in one place.
- Line 62 compares each tab's position with
selectedIndex.
So the property reflects the attribute: it reads it and writes it, as lesson 5.1 built for the tea label. Set either one, and the tabs draw again. Try it:
<tea-tabs selected="1"> <button slot="tab">Green</button> <button slot="tab">Black</button> <button slot="tab">Oolong</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section> <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const tabs = document.querySelector("tea-tabs"); console.log("Before:", tabs.selectedIndex); tabs.selectedIndex = 2; console.log("After:", tabs.getAttribute("selected"));</script>Line 14 writes selected="2". The attribute is observed, so attributeChangedCallback() draws the tabs again: Oolong is bold, and its panel shows.
Line 1 sets selected="1" in the HTML, so line 13 prints Before: 1. Line 14 sets the property. Line 15 reads the attribute, and it always matches what line 14 wrote.
attributeChangedCallback(), and #render() shows Oolong's panel. Reading selectedIndex reads the attribute back.Why does selected="1" on line 1 work with no extra code? MDN explains: when an element is parsed with an observed attribute, attributeChangedCallback() runs for it too. So the first drawing already knows the number.
Two parts of the card wait for the next lesson. Clicks and keys don't change the tab yet, and tea-change isn't sent yet. Lesson 10.2 adds both. It also handles the edge cases: a number past the last tab, and a selectedIndex set before the class loads.
Adding the tabs to the tea kit
The finished file is now tea-kit/tea-tabs.js in Ravi's kit. tea-kit/custom-elements.json lists its attribute, its property, and its two slots. Here the brewing guide turns into a menu: each panel holds a kit tea card.
<tea-tabs selected="2"> <button slot="tab">Green</button> <button slot="tab">Black</button> <button slot="tab">Oolong</button> <section slot="panel"><tea-card name="Green tea" price="4"></tea-card></section> <section slot="panel"><tea-card name="Black tea" price="3"></tea-card></section> <section slot="panel"><tea-card name="Oolong" price="5"></tea-card></section></tea-tabs> <script type="module"> import "./tea-kit/index.js"; document.addEventListener("tea-add", (event) => { console.log(event.tea + ":", event.quantity); });</script>- Line 1 opens on Oolong, with
selected="2". - Lines 5 to 7 put a
tea-cardin each panel. - Line 11 loads the whole kit, tabs included.
- Lines 12 to 14 listen for the card's
tea-addevent from lesson 9.2.
Press Add 1 on the Oolong card. The console prints Oolong: 1. Press +, then Add 2, and it prints Oolong: 2. The tabs don't get in the way. The card is still the page's own element, and its composed event reaches the document as before.
Common mix-ups
- "The host should be the tab list." No. The host holds the panels too. Put
role="tablist"on the row around the tab slot. - "Setting the role in the constructor is fine, since my page works." No. Tags in the HTML upgrade fine, but
createElement()reports aNotSupportedError. Set it inconnectedCallback(). - "A component should set its own role, whatever the page wrote." No. Check
hasAttribute()first. The page's choice wins. - "hidden always hides an element." No. It works through a built-in rule, and any
displayrule you write beats it. Add:host([hidden]). - "Each tab needs its own slot." No. Many children can share one slot name. They show in page order.
- "aria-controls can point into a shadow root." No. An id only finds elements in its own tree. Reference Target changes that, but only in Chrome 152 and later.
- "Setting selectedIndex should fire tea-change." No. The page already knows what it set. The event is for the reader's own picks, in lesson 10.2.
Practice exercises
For each one, ask which tree each element is in, and when each line of the class runs.
The finished tabs are in the tea-tabs.js tab. What does line 4 print?
<script type="module"> import "./tea-tabs.js"; const tabs = document.createElement("tea-tabs"); console.log(tabs.getAttribute("role")); document.body.append(tabs); console.log(tabs.getAttribute("role"));</script>null. createElement() runs only the constructor, which adds no attributes. Line 5 puts the tabs on the page, so connectedCallback() runs, and line 6 prints presentation.
The loop prints each panel's id. What does the second line print?
<tea-tabs> <button slot="tab" id="oolong">Oolong</button> <button slot="tab">Chai</button> <section slot="panel">Steep oolong for 3 minutes.</section> <section slot="panel">Steep chai for 5 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; for (const panel of document.querySelectorAll('[slot="panel"]')) { console.log(panel.id); }</script>tea-tab-1-panel. The first line is oolong-panel, from the page's own id. Chai's tab has no id, so it becomes tea-tab-1, and its panel tea-tab-1-panel.
Fix the class so createElement() works. What does the fixed page print?
<main></main> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.setAttribute("role", "presentation"); } } customElements.define("tea-tabs", TeaTabs); const tabs = document.createElement("tea-tabs"); document.querySelector("main").append(tabs); console.log(tabs.getAttribute("role"));</script><main></main> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { if (!this.hasAttribute("role")) this.setAttribute("role", "presentation"); } } customElements.define("tea-tabs", TeaTabs); const tabs = document.createElement("tea-tabs"); document.querySelector("main").append(tabs); console.log(tabs.getAttribute("role"));</script>presentation. createElement() now gets an element with no attributes, as it expects. The role arrives when line 17 puts the tabs in main.
Fix lines 2 and 3. What does the fixed page print?
<tea-tabs> <button slot="tabs">Green</button> <button slot="tabs">Black</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const tabSlot = document.querySelector("tea-tabs").shadowRoot.querySelector('slot[name="tab"]'); console.log("Tabs:", tabSlot.assignedElements().length);</script><tea-tabs> <button slot="tab">Green</button> <button slot="tab">Black</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const tabSlot = document.querySelector("tea-tabs").shadowRoot.querySelector('slot[name="tab"]'); console.log("Tabs:", tabSlot.assignedElements().length);</script>Tabs: 2. With slot="tab", both buttons go to the tab slot. #render() then pairs them with the panels and hides Black's.
This version builds the tab inside its shadow root, and the page writes the panel. What does the console print?
<tea-tabs> <section slot="panel" role="tabpanel" aria-labelledby="green">Steep green tea for 2 minutes.</section></tea-tabs> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <div role="tablist"><button id="green" role="tab">Green</button></div> <slot name="panel"></slot>`; } } customElements.define("tea-tabs", TeaTabs); const panel = document.querySelector("section"); console.log("Labels:", panel.ariaLabelledByElements.length);</script><tea-tabs> <button slot="tab" id="green" role="tab">Green</button> <section slot="panel" role="tabpanel" aria-labelledby="green">Steep green tea for 2 minutes.</section></tea-tabs> <script> class TeaTabs extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = ` <div role="tablist"><slot name="tab"></slot></div> <slot name="panel"></slot>`; } } customElements.define("tea-tabs", TeaTabs); const panel = document.querySelector("section"); console.log("Labels:", panel.ariaLabelledByElements.length);</script>Labels: 0. The panel looks for green in the page's tree, and the button is in the shadow root. The fix lets the page write the tab with slot="tab", so both ends share one tree, and it prints Labels: 1.
Add a label attribute that names the tab list, as the APG asks. What does your page print?
<tea-tabs label="Brewing guide"> <button slot="tab">Green</button> <button slot="tab">Black</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const row = document.querySelector("tea-tabs").shadowRoot.querySelector('[role="tablist"]'); console.log(row.getAttribute("aria-label"));</script><tea-tabs label="Brewing guide"> <button slot="tab">Green</button> <button slot="tab">Black</button> <section slot="panel">Steep green tea for 2 minutes.</section> <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module"> import "./tea-tabs.js"; const row = document.querySelector("tea-tabs").shadowRoot.querySelector('[role="tablist"]'); console.log(row.getAttribute("aria-label"));</script>Brewing guide. The solution's tea-tabs.js tab watches label and copies it onto the tab row. The row is in the shadow root, so the page can't name it with an id. An attribute on the host can.
Check your understanding
For each question, ask which tree the element is in, and which callback runs the line.
Question 1 of 7Why can't the tabs give the host its role in the constructor?
Choose an answer to see the explanation.
Question 2 of 7Which element of
tea-tabsgetsrole="tablist"?Choose an answer to see the explanation.
Question 3 of 7What does the second console line of step 1's page print?
Read the code, then predict<tea-tabs></tea-tabs> <tea-tabs role="region" aria-label="Brewing guide"></tea-tabs> <script type="module"> import "./tea-tabs.js"; for (const tabs of document.querySelectorAll("tea-tabs")) { console.log(tabs.getAttribute("role")); } </script>Choose an answer to see the explanation.
Question 4 of 7A shadow root's only host rule is
:host { display: block; }. What happens to<tea-tabs hidden>?Choose an answer to see the explanation.
Question 5 of 7Why do the tabs and the panels both stay in the page's light DOM?
Choose an answer to see the explanation.
Question 6 of 7What does
tabs.selectedIndex = 2do in the finished tabs?Choose an answer to see the explanation.
Question 7 of 7In this lesson's tabs, what happens when the reader clicks Black?
Choose an answer to see the explanation.
Key takeaways
- Sketch the API before the code: attributes, properties, events, slots, and what you leave out.
- Make the template once. Attach the shadow root and add listeners in the constructor, never attributes.
- Give the host defaults like
roleinconnectedCallback(), only if the page wrote none. - Pair
:host { display: block; }with:host([hidden]) { display: none; }. - The tab row in the shadow root is the tab list. The host is only a wrapper.
- Many children can share one named slot. They show in page order.
- Keep tabs and panels in the page's tree, so
aria-controlsandaria-labelledbyfind their ids. selectedIndexreads and writes theselectedattribute. Observing it makes every change draw again.
Remember the one-liner.
The shadow root is the frame, the page's tabs and panels are the content, and ids link them inside one tree.
Sources
The facts on this page come from these standards, docs, and source files:
- HTMLSelectElement: selectedIndex property, MDN.
- Custom element best practices, web.dev.
- tab-container-element source, GitHub.
- HTML Standard: Requirements for custom element constructors and reactions, WHATWG.
- ElementInternals: role property, MDN.
- HTML Standard: Hidden elements, WHATWG.
- WAI-ARIA: tablist role, W3C.
- Inclusive Components: Tabbed interfaces, Heydon Pickering.
- Using templates and slots: Adding flexibility with slots, MDN.
- Using templates and slots: Named and manual slot assignment, MDN.
- WAI-ARIA APG: Tabs pattern, W3C.
- ::slotted(), MDN.
- Element: ariaControlsElements property, MDN.
- Attribute reflection: Element id reference scope, MDN.
- Chrome 152 release notes: Reference Target for cross-root ARIA, Chrome for Developers.
- Using custom elements: Responding to attribute changes, MDN.
Coming next: Adding selection and events to the tabs. It makes the tabs select with clicks and keys, keeps the attribute and property in sync, and sends tea-change.