completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Focus and shadow DOM

Learn how shadow DOM focus works: document.activeElement and shadowRoot.activeElement, delegatesFocus, tab order, :focus-within on the host, and relatedTarget.

By the end, you can
  • 01
    Find where focus really isRead document.activeElement and each shadow root's activeElement, and walk down to the element that has focus.
  • 02
    Make a host take focus like a controlUse delegatesFocus and autofocus to choose which inner element gets focus, and style the host with :focus-within.
  • 03
    Predict tab order and focus eventsSay where a component's controls come in the tab order, and which listeners hear focusin and focusout, with which relatedTarget.

How does focus work in shadow DOM?

Asha is building Leaf and Kettle's order page. Ravi gave her a small part for it, <tea-quantity>. It has a - button, a number box, and a + button. Asha wants her page to know where the reader is typing. She asks document.activeElement. The answer is tea-quantity. But the cursor is in the number box. So where is the focus, really?

In shadow DOM, focus goes to the real element inside the shadow root, but the page only sees the host. document.activeElement gives the outermost host. The shadow root's own activeElement gives the element inside. And with delegatesFocus: true, focusing the host hands focus to an element inside, so the host acts like one control.

First, a reminder from lesson 3.5. Focus is where your key presses go: the box you type in, or the button that Enter presses. Only one element has it at a time. You move it by clicking, or by pressing Tab. Keyboard and focus covers focus on a page without shadow DOM. Here is Ravi's quantity, and a page that asks where focus is:

The page and the shadow root say where focus isPop out in the code editor (opens in a new tab)HTML
<tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const quantity = document.querySelector("tea-quantity");  document.addEventListener("focusin", () => {    console.log("The page says:", document.activeElement.localName);    console.log("The shadow root says:", quantity.shadowRoot.activeElement.id);  });</script>
ResultLoading…
  • In the tea-quantity.js tab, line 4 attaches a shadow root. Lines 6 to 8 put three controls in it, with the ids less, count, and more. Lines 9 to 11 make the buttons change the number.
  • On the page, line 6 listens for focusin on the document. That event fires when an element gets focus, and it bubbles up to the page.
  • Line 7 prints what the page sees. Line 8 asks the quantity's shadow root, and prints the id it gives.

Click in the number box. The console prints The page says: tea-quantity, then The shadow root says: count. One focus, two answers. The page sees only the host, the element the shadow root belongs to. The shadow root knows which of its own elements has focus.

Now click +. Nothing new prints. Focus moved from the number box to the + button, but the page never heard about it. The section on focus events explains why.

Two windows. Left, the page: one card, tea-quantity, labelled document.activeElement. An arrow leads right, into the quantity's shadow root: three cards, -, count, and +, with count labelled shadowRoot.activeElement.pagetea-quantitydocument.activeElementshadow root-count+shadowRoot.activeElement
The cursor is in the number box. The page only sees the host, tea-quantity. The shadow root knows which of its elements has focus: count.
Real-life analogyThe school office knows the class, not the desk

Asha's mum phones the school. The office says, "Asha is in class 4B." That's all the office knows. To learn that she's at the reading table, you ask 4B's teacher.

In real life: The school office
In JavaScript: document.activeElement
In real life: "Asha is in class 4B"
In JavaScript: The host, tea-quantity
In real life: 4B's teacher
In JavaScript: quantity.shadowRoot.activeElement
In real life: "At the reading table"
In JavaScript: The number box, count
The main idea

Focus inside a shadow root shows up as the host to everything outside it. Each tree reports the nearest element it holds. A host can also take focus like a built-in control, by handing it to an element inside.

You met the first half in lesson 6.3. The HTML Standard spells it out: when the focused element is in another tree, a tree's activeElement gives the host that sits in that tree.

Why it matters: the page can't see a component's inside, and that includes focus. Code that asks "where is the reader typing?" has to ask the right tree. This lesson covers five things: activeElement, delegatesFocus, tab order, focus styles on the host, and the focus events with their relatedTarget.

How do you find the focused element in a shadow root?

Components hold other components. Ravi puts the quantity inside a tea card, in the card's shadow root. Now focus can sit two shadow roots deep. What does each tree say?

Focus two shadow roots deepPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-quantity.js"></script><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const quantity = card.shadowRoot.querySelector("tea-quantity");  document.addEventListener("focusin", () => {    console.log("document:", document.activeElement.localName);    console.log("card's root:", card.shadowRoot.activeElement.localName);    console.log("quantity's root:", quantity.shadowRoot.activeElement.id);  });</script>
ResultLoading…
  • In the tea-card.js tab, line 5 puts a heading and a tea-quantity in the card's shadow root.
  • On the page, line 6 finds the card. Line 7 finds the quantity inside the card's shadow root.
  • Lines 9 to 11 ask three trees where focus is: the document, the card's root, and the quantity's root.

Click in the number box. The console prints document: tea-card, then card's root: tea-quantity, then quantity's root: count. Each tree names the nearest element it holds, like the desks in lesson 9.1. The document only knows the card. The card's root knows the quantity. Only the quantity's root knows the number box.

Westbrook Johnson calls this out: document.activeElement points to the host in the document, not to the link or box inside it. So to find the element that really has focus, start at the document and walk down:

Walking down to the element that has focusPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-quantity.js"></script><script src="tea-card.js"></script><script>  function focusedElement() {    let element = document.activeElement;    while (element?.shadowRoot?.activeElement) {      element = element.shadowRoot.activeElement;    }    return element;  }   document.addEventListener("focusin", () => {    console.log("Focused:", focusedElement().id);  });</script>
ResultLoading…
  • Line 7 starts with what the document sees, tea-card.
  • Line 8 asks: does this element have a shadow root, and does that root report an activeElement? The ?. stops the check early, with undefined, if a part is missing.
  • Line 9 steps one tree down. The loop runs twice here: from the card to the quantity, then from the quantity to the number box.
  • Line 11 gives back the element where the loop stopped.

Click in the number box. The console prints Focused: count. The same loop appears in web.dev's guide to shadow DOM.

The loop stops at a closed shadow root. Its host's shadowRoot is null, as lesson 6.2 showed. That's fair: a closed component keeps its focus private too. Walking the tree in other ways, like finding the root any node lives in, is the topic of Walking the composed tree, the next lesson.

Why it matters: a lot of page code checks document.activeElement. A keyboard shortcut that should stay quiet while the reader types is a common one. With shadow DOM, that check sees a host, not a text box, and the shortcut fires in the middle of typing. Exercise 4 fixes exactly that bug.

What does delegatesFocus do?

Asha adds a Choose cups button to her page. It should move focus into the quantity, so the reader can pick a number right away. On a text box, she'd call focus(). Does that work on the quantity?

Try it. The first choice is the quantity as Ravi wrote it. The second turns on delegatesFocus, an option of attachShadow(). The third also marks the number box with autofocus.

Playground: where does quantity.focus() put focus?
A Choose cups button that calls quantity.focus()Pop out in the code editor (opens in a new tab)HTML
<button id="choose">Choose cups</button><tea-quantity></tea-quantity> <script>  class TeaQuantity extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `        <span>Cups:</span>        <button id="less" aria-label="One cup less">-</button>        <input id="count" type="number" min="1" value="1" aria-label="Cups">        <button id="more" aria-label="One cup more">+</button>`;    }  }  customElements.define("tea-quantity", TeaQuantity);   const quantity = document.querySelector("tea-quantity");  document.querySelector("#choose").addEventListener("click", () => quantity.focus());  quantity.addEventListener("focusin", () => {    console.log("Focused:", quantity.shadowRoot.activeElement.id);    console.log("The host matches :focus:", quantity.matches(":focus"));  });</script>
ResultLoading…
Try it yourself
focus() does nothing

Nothing prints when you click Choose cups, or the word Cups. The host isn't a control, so quantity.focus() has nowhere to put focus. Click in the number box itself, and it prints Focused: count and The host matches :focus: true.

Only lines 8 and 12 change. Click Choose cups in the result, then click the word Cups. The quantity prints where focus landed.
  • Line 8 attaches the shadow root. The playground adds delegatesFocus: true to its options.
  • Line 10 is plain text, Cups:. Lines 11 to 13 are the three controls. Line 12 is the one that can get autofocus.
  • Line 19 calls quantity.focus() when Choose cups is clicked.
  • Lines 20 to 23 print which element inside got focus, and whether the host matches :focus.

With the first choice, clicking Choose cups prints nothing. A custom element with no tabindex isn't a control, so it can't take focus itself. focus() on it does nothing, quietly. Clicking the word Cups does nothing either.

Now pick delegatesFocus: true and click Choose cups. It prints Focused: less and The host matches :focus: true. The host passed focus to the first element inside that can take it, the - button. Click somewhere else, then click the word Cups. The same two lines print. A click on any part that can't take focus is handed on too. MDN describes both: a call to focus() on the host, and a click on a part that can't take focus.

Real-life analogyA host at the door walks you to your table

You walk into Leaf and Kettle and say, "A table, please." You asked the shop, not a table. The host at the door walks you to the first free table. If a table has a card with your name on it, she takes you there instead.

In real life: Asking the shop for a table
In JavaScript: quantity.focus(), or a click on plain text
In real life: The host at the door
In JavaScript: delegatesFocus: true
In real life: The first free table
In JavaScript: The first element inside that can take focus
In real life: The table with your name card
In JavaScript: The element with autofocus

Which element gets focus?

Now pick the third choice and click Choose cups. It prints Focused: count. The number box won, though the - button comes first.

Two rows of the quantity's shadow root, in tree order: Cups:, -, count, +. Without autofocus: the first one that can take focus: an arrow points at -, and the other cards are faded. With autofocus on count: that one first: an arrow points at count, and the other cards are faded. On the right: the browser checks for an autofocus element first, then takes the first one that can take focus.Without autofocus: the first one that can take focusCups:-count+gets focusWith autofocus on count: that one firstCups:-count+gets focusThe browser checks:1. an autofocus element2. else the first one,in tree order, thatcan take focus
With delegatesFocus: true, quantity.focus() hands focus to one element inside. The faded ones don't get it. Cups: is plain text, so it can never take focus.

The HTML Standard calls the chosen element the focus delegate. It picks it in two steps:

  1. An element in the shadow root with the autofocus attribute.
  2. If there isn't one, the first element that can take focus, in tree order: the order the elements appear in the markup.

Tree order isn't tab order. A tabindex that changes the Tab order doesn't change the choice. Even an element that Tab skips, with tabindex="-1", counts. Exercise 2 tries it.

Use autofocus with care. MDN warns it can make people miss what comes before the element. Usually the simpler fix is to put the most useful control first.

A few more facts about a host that delegates focus:

  • The host itself never has focus. The element inside does, and the host matches :focus.
  • If focus is already inside, focus() leaves it where it is. The standard checks that first.
  • quantity.shadowRoot.delegatesFocus reads the option back. Here it's true.
  • In Lit, a component sets static shadowRootOptions to { ...LitElement.shadowRootOptions, delegatesFocus: true }, as Lit's docs show.

Why it matters: delegatesFocus makes a component act like one control. Pages can call focus() on it, and clicks on its text land somewhere useful. It suits small controls like a quantity, a button, or a text field. It suits a big box badly: on a card, a click on any text would jump focus to its first button. Lesson 14.1, in Accessible components, goes deeper: a tabindex on the host, and focus rings that only show for the keyboard.

Safari had the option from 13.1, and the shadowRoot.delegatesFocus property from Safari 15.

How does tab order work across shadow roots?

Pressing Tab moves focus to the next control. Shift+Tab moves it back. The tabindex attribute changes that order, as Keyboard and focus showed:

  • tabindex="0" puts an element in the normal order.
  • tabindex="-1" lets code focus it, but Tab skips it.
  • A positive number, like 1, sends it ahead of the normal order.

Ravi wants the + button to come first in his quantity, so he gives it tabindex="1". Will it jump ahead of the whole page? Try it, and compare with a tabindex="1" on the page's own After button:

Playground: where does tabindex="1" take effect?
Before, a quantity, and AfterPop out in the code editor (opens in a new tab)HTML
<button id="before">Before</button><tea-quantity></tea-quantity><button id="after">After</button> <script>  class TeaQuantity extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `        <button id="less" aria-label="One cup less">-</button>        <input id="count" type="number" min="1" value="1" aria-label="Cups">        <button id="more" aria-label="One cup more">+</button>`;    }  }  customElements.define("tea-quantity", TeaQuantity);   document.addEventListener("keyup", (event) => {    if (event.key === "Tab") console.log(event.composedPath()[0].id);  });</script>
ResultLoading…
Try it yourself
Tree order, with the quantity in its place

Click Before, then press Tab four times. The console prints less, count, more, after. The quantity's three controls come at the host's place on the page, in tree order.

Only line 3 or line 13 changes. Each time Tab lands on something in the result, the page prints its id.
  • Lines 1 to 3 are the page: Before, the quantity, and After. Line 3 is the page's button the playground changes.
  • Lines 11 to 13 are the quantity's controls. Line 13 is the + button the playground changes.
  • Lines 18 to 20 print the id of the element each Tab lands on. keyup is composed and bubbles, so the page hears it from inside the quantity. composedPath()[0] is the element where it started, as in lesson 9.1.

Why keyup, not focusin? Because the page doesn't hear focusin when focus moves inside the quantity, as the first example showed.

With no tabindex, click Before and press Tab four times. The console prints less, count, more, after. The quantity's three controls come at the host's place, in tree order.

With tabindex="1" on +, it prints more, less, count, after. The + button moved to the front, but only inside the quantity. Before still comes first.

With tabindex="1" on After, After is first on the whole page. Click After and press Tab four times: before, less, count, more.

Tab order with tabindex 1 on the + button inside the quantity. A card before, an arrow, then a window called shadow root holding more, less, and count, joined by arrows, with tabindex 1 written above more. Then an arrow to a card after.beforeshadow roottabindex="1"morelesscountafterthe quantity's own order, at the host's place on the page
Tab visits Before, then the quantity's three controls, then After. tabindex="1" moves more to the front, but only inside the quantity's own group.

The HTML Standard explains it with groups. It calls them focus navigation scopes. The document owns one. Every shadow host owns one too, holding the elements of its shadow root. So does every slot, holding what's slotted into it. Then:

  • Inside each group, tabindex sorts the order: positive numbers first, then the rest in tree order.
  • A group goes into its owner's place. A host's group goes where the host is in the page's order.
  • The browser repeats this down to the last nested group, and gets one long list.

The standard calls that list the flattened tabindex-ordered focus navigation scope. A positive tabindex never leaves its group. Lesson 36.5, in Under the hood, follows these steps inside the browser.

Real-life analogyA waiter serves table by table

At Leaf and Kettle, the waiter serves table by table, around the room. At table 2, she serves the child first. But table 2 still waits for table 1. The child goes first at her own table, not in the whole room.

In real life: The tables, in order around the room
In JavaScript: The page's order, with each host in its place
In real life: The guests at one table
In JavaScript: The controls in one shadow root
In real life: Serving the child at table 2 first
In JavaScript: tabindex="1" inside the component
In real life: Table 1 is still served before table 2
In JavaScript: Before still comes before the quantity

Slots follow the same rule. A slotted button is the page's own element, but in the tab order it sits where its slot is. That's the order the reader sees, the flat tree from lesson 8.2. Exercise 6 tries it.

Why it matters: a component can order its own controls without breaking the page's order, and the page can't reorder the component's inside either. Positive values are still hard to follow, so use them rarely. And code that lists the page's focusable elements with querySelectorAll() misses every shadow root. Nolan Lawson shows how that breaks older focus trap libraries.

How do :focus and :focus-within match the host?

Lesson 6.3 showed that a host matches :focus and :focus-within while something in its shadow root has focus. The HTML Standard says a host has the focus, for :focus, when its shadow root holds the focused element. That's true with or without delegatesFocus: the playground's first choice printed true when you clicked in the number box.

Inside the component, :host() styles the host when it matches a selector. So :host(:focus-within) styles the host while focus is anywhere in it. Are the two selectors the same, then? Not when slots are involved. Here is a note with its own text box, and a slot for the page's Save button:

A note with a slotted Save buttonPop out in the code editor (opens in a new tab)HTML
<tea-note>  <button id="save">Save</button></tea-note> <script src="tea-note.js"></script><script>  const note = document.querySelector("tea-note");  note.addEventListener("focusin", (event) => {    console.log("Focus on", event.composedPath()[0].id);    console.log(":focus", note.matches(":focus"), ":focus-within", note.matches(":focus-within"));  });</script>
ResultLoading…
  • In the tea-note.js tab, line 8 draws a dashed ring while focus is within the host. Line 9 makes it solid while the host matches :focus.
  • Line 11 is the note's own text box. Line 12 is a slot.
  • On the page, line 2 is the page's own Save button, shown in the slot. Lines 8 to 11 ask the note, from outside, which pseudo-classes match.

Click in the Note box. The console prints Focus on note and :focus true :focus-within true, and the ring is solid. Now click Save. It prints Focus on save and :focus false :focus-within true, and the ring turns dashed.

Save is the note's child, so focus is within the note. But Save lives in the page's tree, not in the shadow root, so the host doesn't have the focus. Read each row of the table across:

Does each selector match the note?
Where focus isDoes :host(:focus) match?Does :host(:focus-within) match?
In the note's own text box, inside its shadow root.Yes.Yes.
In the page's Save button, shown in the note's slot.No.Yes.
In somewhere else on the page.No.No.

The page's own CSS sees the same thing. tea-note:focus-within and tea-note:focus follow the same rows. MDN notes that :focus-within counts descendants in shadow trees.

Why it matters: for a ring around the whole component, use :host(:focus-within). It lights up for the component's own controls and for anything slotted. It's like a lamp on a market stall that's on while anyone at the stall is being served. Rings that only show for keyboard users, and colors that are easy to see, come in lesson 14.1.

Which focus events does the page hear?

Lesson 9.2 showed that focus events are composed: they may leave a shadow root. focus and blur don't bubble. focusin and focusout do, so the page hears them. When focus moves, they fire in this order, says MDN:

  1. blur, then focusout, on the element losing focus.
  2. focus, then focusin, on the element getting focus.

Each one also carries relatedTarget: the other element in the move. For focusout, it's the element getting focus. For focusin, it's the element that lost it. It's null when there's no other element, like when focus comes in from outside the page. Here are three listeners, inside and outside the quantity:

focusin and focusout, heard in three placesPop out in the code editor (opens in a new tab)HTML
<button id="before">Before</button><tea-quantity></tea-quantity><button id="after">After</button> <script src="tea-quantity.js"></script><script>  const quantity = document.querySelector("tea-quantity");  const name = (node) => (node ? node.id || node.localName : "null");  function log(where, event) {    console.log(`${where}: ${event.type} ${name(event.target)}, related ${name(event.relatedTarget)}`);  }  for (const type of ["focusin", "focusout"]) {    quantity.shadowRoot.addEventListener(type, (event) => log("root", event));    quantity.addEventListener(type, (event) => log("host", event));    document.addEventListener(type, (event) => log("document", event));  }</script>
ResultLoading…
  • Line 8 turns a node into a short name: its id, or its tag name, or null.
  • Lines 9 to 11 print where the listener is, the event's type, its target, and its relatedTarget.
  • Lines 13 to 15 listen in three places: the shadow root, the host, and the document.

Click Before. The console prints document: focusin before, related null. Then press Tab four times.

The first Tab enters the quantity. Four lines print. The document hears focusout from Before, with related tea-quantity. Then the root hears focusin less, related before. The host and the document hear focusin tea-quantity, related before.

The second and third Tabs move inside the quantity. Only the root hears them. It prints focusout less, related count and focusin count, related less, then the same again for more.

The fourth Tab leaves. The root hears focusout more, related after. The host and the document hear focusout tea-quantity, related after. Last, the document hears focusin after, related tea-quantity.

Three rows of cards: the path of three focus events. focusin, Tab from Before to -: less, ShadowRoot, tea-quantity, body, html, document. focusin, Tab from - to the number box: count, ShadowRoot, tea-quantity (not reached), body (not reached), html (not reached), document (not reached). focusout, Tab from + to After: more, ShadowRoot, tea-quantity, body, html, document. In each row, a dashed line marks the edge of the quantity's shadow root.focusin, Tab from Before to -lessShadowRoottea-quantitybodyhtmldocumentfocusin, Tab from - to the number boxcountShadowRoottea-quantitybodyhtmldocumentfocusout, Tab from + to AftermoreShadowRoottea-quantitybodyhtmldocumentthe edge of the quantity's shadow root
Focus entering or leaving the quantity reaches the host and the page. A move between two of its own controls stops at its shadow root: outside, both ends of the move would be tea-quantity.

Why does the page miss the moves inside? Lesson 9.1 showed that the browser retargets event.target for each listener. It retargets relatedTarget the same way. For a move from less to count, the host would read the target as tea-quantity and the related element as tea-quantity too. Focus moved from the quantity to the quantity. That's no news, so the event stops before the host.

The DOM Standard writes this into the steps for dispatching an event. While it builds the path, if the next node up is the retargeted relatedTarget itself, the path ends there.

Real-life analogyThe door bell rings only at the door

The bell over Leaf and Kettle's door rings when a customer comes in or goes out. It doesn't ring when they move from one table to another. The staff inside see every move anyway.

In real life: The bell over the door
In JavaScript: focusin and focusout on the host and the page
In real life: A customer walking in or out
In JavaScript: Focus entering or leaving the component
In real life: Moving from one table to another
In JavaScript: Focus moving between two controls inside
In real life: The staff, who see every move
In JavaScript: Listeners on the shadow root

relatedTarget inside and outside

Look at the values again. Inside the root, relatedTarget showed the page's buttons as they are: before and after. The page's own elements are public. Outside, the quantity's controls showed up as tea-quantity, just like targets. So a listener never learns more than its own tree holds, from either property.

Does the page hear it?
  • Tab from the page's Before button to the quantity's - button
  • Tab from the quantity's - button to its number box
  • Tab from the quantity's + button to the page's After button
  • Tab from one quantity's + button to the next quantity's - button
  • Tab from the + button of a quantity inside a card to the card's Add button
  • Click from the page's Before button to its After button
Try it yourself
0 of 6 correct

Sort each move of focus by who hears focusin and focusout.

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

Why it matters: a component can tell when focus leaves it as a whole. Listen for focusout on the host itself. It runs when focus goes out to the page, not on every move inside. If the component has slotted controls, also check this.contains(event.relatedTarget). A slotted control is the host's own child, so focus moving to it hasn't really left.

Making the kit's quantity take focus like one control

Time to put this in Ravi's kit. Since lesson 9.2, every tea card holds a private tea-quantity: a number between a - and a + button. In the example below, open the tea-kit/tea-quantity.js tab. Two things changed:

  • Line 23 attaches its shadow root with delegatesFocus: true. A click on its number now lands on the - button.
  • Line 5 draws a sea green ring with :host(:focus-within) while either button has focus.

Here are two kit cards, and a page that prints which card and which control focus lands on:

Two kit cards, and where focus landsPop out in the code editor (opens in a new tab)HTML
<tea-card name="Green tea" price="4"></tea-card><tea-card name="Oolong" price="5"></tea-card> <script type="module">  import "./tea-kit/index.js";   function focusedElement() {    let element = document.activeElement;    while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;    return element;  }   document.addEventListener("focusin", (event) => {    const control = focusedElement();    console.log(`${event.target.getAttribute("name")}: ${control.getAttribute("aria-label") ?? control.textContent}`);  });</script>
ResultLoading…
  • Lines 1 and 2 are two cards. Line 5 loads the kit.
  • Lines 7 to 11 are the loop from earlier. Its while fits on line 9.
  • Lines 13 to 16 listen for focusin on the page. Line 15 prints the card's name, from event.target, and the control's label.

Click the number 1 on the Green tea card. The console prints Green tea: One cup less, and the ring appears around the quantity. The number can't take focus, so the quantity handed it to its first button.

Now press Tab twice. Focus goes to +, then to Add 1. Nothing prints, and the ring goes away on Add 1. Every move so far stayed inside the Green tea card, so the page heard none of them. Press Tab once more. Focus enters the next card, and the page prints Oolong: One cup less.

Why not delegate focus on the card too? A card is a big box with a name, a price, and notes. With delegatesFocus, a click on any of that text would jump focus to the card's first button. The quantity is small, and it acts as one control, so it's the right place.

Common mix-ups

  • "document.activeElement is the element that has focus." No. With shadow DOM, it's the outermost host. Walk down through each shadowRoot.activeElement to find the element.
  • "A tabindex of 1 inside a component jumps ahead of the page." No. It sorts only the component's own controls. The whole component still comes at the host's place.
  • "delegatesFocus picks the first element in tab order." No. It picks an autofocus element first, then the first in tree order. Even a tabindex="-1" element counts.
  • "focus() works on any custom element." No. A host without delegatesFocus or a tabindex can't take focus, so focus() does nothing.
  • "The host matches :focus only with delegatesFocus." No. It matches whenever its shadow root holds the focused element.
  • ":host(:focus) and :host(:focus-within) always agree." No. When a slotted element has focus, only :focus-within matches.
  • "The page hears focusin and focusout as focus moves between a component's controls." No. Outside, the target and relatedTarget would both be the host, so the events stop inside.
  • "relatedTarget shows the real element everywhere." No. It's retargeted like target. Outside a shadow root, an element inside shows up as the host.

Practice exercises

For each one, ask which tree you're in, and which element that tree can see. Then check in the result.

Exercise 1 · Warm-upFocus two roots deep

Click in the number box. What does the console print?

<tea-card></tea-card> <script src="tea-quantity.js"></script><script src="tea-card.js"></script><script>  document.addEventListener("focusin", () => {    console.log(document.activeElement.localName);  });</script>
ResultLoading…

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

    Exercise 2 · Warm-upTree order or tab order?

    Click Choose cups. Which id prints?

    <button id="choose">Choose cups</button><tea-quantity></tea-quantity> <script>  class TeaQuantity extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `        <button id="less" aria-label="One cup less">-</button>        <button id="more" tabindex="1" aria-label="One cup more">+</button>`;    }  }  customElements.define("tea-quantity", TeaQuantity);   const quantity = document.querySelector("tea-quantity");  document.querySelector("#choose").addEventListener("click", () => {    quantity.focus();    console.log(quantity.shadowRoot.activeElement.id);  });</script>
    ResultLoading…

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

      Exercise 3 · PracticePut the cursor in the number box

      Choose cups should put the cursor in the number box. Change the quantity, not the page. What does the fixed page print?

      <button id="choose">Choose cups</button><tea-quantity></tea-quantity> <script>  class TeaQuantity extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `        <button id="less" aria-label="One cup less">-</button>        <input id="count" type="number" min="1" value="1" aria-label="Cups">        <button id="more" aria-label="One cup more">+</button>`;    }  }  customElements.define("tea-quantity", TeaQuantity);   const quantity = document.querySelector("tea-quantity");  document.querySelector("#choose").addEventListener("click", () => {    quantity.focus();    console.log("Focused:", quantity.shadowRoot.activeElement?.id ?? "nothing");  });</script>
      ResultLoading…

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

        Exercise 4 · PracticeThe shortcut fires while you type

        Type hot in the Note box. The page prints Help opened, which it shouldn't. What is document.activeElement.localName while you type? Then fix the check.

        <p>Press h for help.</p><tea-note></tea-note> <script src="tea-note.js"></script><script>  const typing = () => document.activeElement.localName === "input";  document.addEventListener("keydown", (event) => {    if (typing()) return;    if (event.key === "h") console.log("Help opened");  });</script>
        ResultLoading…

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

          Exercise 5 · ChallengeLeaving the quantity, inside the card

          Four places listen for focusout. Click +, then press Tab. How many lines print?

          <tea-card></tea-card> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = '<tea-quantity></tea-quantity><button id="add">Add</button>';    }  }  customElements.define("tea-card", TeaCard);   const card = document.querySelector("tea-card");  const quantity = card.shadowRoot.querySelector("tea-quantity");  const name = (node) => (node ? node.id || node.localName : "null");  const places = { "quantity's root": quantity.shadowRoot, "card's root": card.shadowRoot, card, document };  for (const [where, node] of Object.entries(places)) {    node.addEventListener("focusout", (event) => {      console.log(`${where}: ${name(event.target)} to ${name(event.relatedTarget)}`);    });  }</script>
          ResultLoading…

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

            Exercise 6 · ChallengeSlotted buttons in the tab order

            Click Before, then press Tab three times. In what order do the card's three buttons get focus? Guess before you try.

            <button id="before">Before</button><tea-card>  <button id="share">Share</button>  <button id="oolong" slot="name">Oolong</button></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = '<h3><slot name="name"></slot></h3><button id="add">Add</button><slot></slot>';    }  }  customElements.define("tea-card", TeaCard);   document.addEventListener("focusin", (event) => console.log(event.composedPath()[0].id));</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask which tree is looking, and what it can see from there.

              The focus and shadow DOM quiz · 8 questionsScore: first tries count
              1. Question 1 of 8The number box of a tea-quantity has focus. The quantity sits in a tea-card's shadow root. What is document.activeElement?

                Choose an answer to see the explanation.

              2. Question 2 of 8In the same page, what does card.shadowRoot.activeElement give?

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this page print first when you click Choose cups?

                Read the code, then predictHTML
                <button id="choose">Choose cups</button>
                <tea-quantity></tea-quantity>
                
                <script>
                  class TeaQuantity extends HTMLElement {
                    constructor() {
                      super();
                      this.attachShadow({ mode: "open", delegatesFocus: true });
                      this.shadowRoot.innerHTML = `
                        <span>Cups:</span>
                        <button id="less" aria-label="One cup less">-</button>
                        <input id="count" type="number" min="1" value="1" aria-label="Cups" autofocus>
                        <button id="more" aria-label="One cup more">+</button>`;
                    }
                  }
                  customElements.define("tea-quantity", TeaQuantity);
                
                  const quantity = document.querySelector("tea-quantity");
                  document.querySelector("#choose").addEventListener("click", () => quantity.focus());
                  quantity.addEventListener("focusin", () => {
                    console.log("Focused:", quantity.shadowRoot.activeElement.id);
                    console.log("The host matches :focus:", quantity.matches(":focus"));
                  });
                </script>

                Choose an answer to see the explanation.

              4. Question 4 of 8The quantity's shadow root doesn't delegate focus, and the host has no tabindex. What does quantity.focus() do?

                Choose an answer to see the explanation.

              5. Question 5 of 8The page has Before, then a tea-quantity, then After. Inside, the + button has tabindex="1". Which element gets focus when you press Tab on Before?

                Choose an answer to see the explanation.

              6. Question 6 of 8Focus moves from the quantity's - button to its number box. Does a focusin listener on document run?

                Choose an answer to see the explanation.

              7. Question 7 of 8The page's Save button sits in a note's slot, and it has focus. Which selector matches the note?

                Choose an answer to see the explanation.

              8. Question 8 of 8Focus leaves the quantity's + button for the page's After button. What does a focusout listener on document read?

                Choose an answer to see the explanation.

              Key takeaways

              • Focus sits on the real element inside a shadow root. document.activeElement gives the outermost host.
              • Each tree's activeElement names the nearest element it holds. Walk down through shadowRoot.activeElement to find the focused element.
              • delegatesFocus: true hands focus from the host to an element inside, on focus() and on clicks on plain text.
              • The element it picks has autofocus, or else it's the first in tree order that can take focus.
              • Each shadow root, and each slot, is its own group in the tab order, placed where its host or slot is.
              • The host matches :focus when its shadow root holds focus. :focus-within also matches for slotted elements.
              • The page hears focusin and focusout only when focus enters or leaves a component.
              • relatedTarget is retargeted like target.

              Remember the one-liner.
              Outside a shadow root, focus inside it looks like the host, and delegatesFocus lets the host take focus like one control.

              Sources

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

              Coming next: Walking the composed tree, the last lesson of module 9. Find the root a node lives in, query across shadow roots, and work with selections that cross them.

              CompleteFrontend Clear concepts. Working examples.