completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

What encapsulation means

Shadow DOM encapsulation explained: which queries, ids, and styles stay inside a shadow root, and how inherited styles, events, and focus still cross it.

By the end, you can
  • 01
    Say what stops at a shadow rootDOM searches, id references, and CSS selectors stop at the boundary, from the page going in and from the component going out.
  • 02
    Use ids safely inside a componentGive a component short ids of its own, and spot the references, like <label for>, that can't cross.
  • 03
    Know what crosses on purposeInherited styles, custom properties, lang, events, and focus cross. An iframe separates far more, at a higher cost.

What does shadow DOM encapsulation mean?

Leaf and Kettle's menu page now shows a tea card for every tea. Ravi built the card. Inside its shadow root, the tea's name sits in a heading with id="name". Asha looks after the page. She counts twelve cards, so twelve headings share one id. "Ids must be unique," she says. "Won't they clash?"

"They can't," Ravi says. "Shadow DOM encapsulates them." Asha asks what that word means, exactly. What stays inside a shadow root, and what gets out?

Shadow DOM encapsulation means a shadow root keeps its own names, styles, and searches to itself. Ids, CSS selectors, and DOM queries stop at the shadow boundary, in both directions. Inherited styles, events, and focus still cross it, on purpose.

Lesson 6.1 showed the page's side of this. This lesson maps the whole boundary, from both sides. Here is Asha's menu, cut down to two cards:

Three headings with id name, in three treesPop out in the code editor (opens in a new tab)HTML
<style>  h3 { color: crimson; }</style><h3 id="name">Our teas</h3><tea-card name="Green tea"></tea-card><tea-card name="Oolong"></tea-card> <script src="tea-card.js"></script><script>  const cards = document.querySelectorAll("tea-card");  console.log(document.querySelectorAll("#name").length);  console.log(cards[0].shadowRoot.getElementById("name").textContent);  console.log(cards[1].shadowRoot.getElementById("name").textContent);</script>
ResultLoading…
  • Line 2 makes every <h3> on the page crimson.
  • Line 4 is the page's heading, Our teas. Its id is name.
  • Lines 5 and 6 are two cards. Their class is in the tea-card.js tab.
  • In that tab, line 6 gives the card an h3 rule of its own: sea green. Line 7 is the card's heading. Its id is name too. Line 10 writes the card's name attribute into it.
  • Back on the page, line 11 counts the elements with the id name that the page can find. It prints 1.
  • Lines 12 and 13 ask each card's shadow root for its own name. They print Green tea and Oolong.

The result shows Our teas in crimson, and Green tea and Oolong in sea green. Three elements share one id, and nothing clashed. The page's h3 rule didn't reach the cards. The cards' h3 rule didn't reach the page. Each tree kept its names and its styles to itself.

Three trees from the first example. A window called page holds h3 id name, which says Our teas, and two tea-card elements. An arrow leads from each tea-card to its own window called shadow root. Each shadow root holds h3 id name: Green tea in the first, Oolong in the second.page<h3 id="name"><tea-card><tea-card>Our teasshadow root<h3 id="name">shadow root<h3 id="name">Green teaOolong
The page's tree and each card's shadow tree are separate. Each tree has one id="name", so there are three on the page and no clash. Each tree's h3 rule colors only its own heading.

The word for this is scope: the area where a name or a rule counts. Each shadow root is a scope of its own.

Real-life analogyA stall in a market hall

The tea stall in a covered market has its own shelves, labelled shelf 1 and shelf 2. The bakery next door uses the same labels, and nobody mixes them up. The hall's rules about displays stop at each stall's counter. But the hall's lights and music reach every stall.

In real life: The market hall
In JavaScript: The page
In real life: A stall, behind its counter
In JavaScript: A component's shadow tree
In real life: The counter
In JavaScript: The shadow boundary
In real life: Shelf 1 at the tea stall, and shelf 1 at the bakery
In JavaScript: id="name" in two shadow roots
In real life: The hall's rules about displays
In JavaScript: The page's CSS selectors and searches
In real life: The hall's lights and music
In JavaScript: Inherited styles, which do cross
The main idea

Encapsulation means scoping. A shadow root is a separate tree with its own ids, its own CSS rules, and its own searches. They stop at the shadow boundary, from both sides. A few things cross on purpose: inherited styles, events, and focus.

Scope isn't secrecy. Lesson 6.2 showed that other scripts can still open a component. The last section of this lesson compares shadow DOM with an iframe, which keeps much more apart.

Does querySelector work across the shadow boundary?

No, and the rule works both ways. Lesson 6.1 showed one side: document.querySelector() can't see into a card. The other side is just as true. Code inside a card can't search the page. And it holds for every way of searching, not only querySelector().

Real-life analogySearching your own garden

You drop your keys in the garden. You search every bed and bush, up to the fence. You don't climb into the neighbour's garden, and the neighbour doesn't search yours. If you want them to look, you walk round and ask at their gate.

In real life: Your garden
In JavaScript: The page's tree
In real life: The neighbour's garden
In JavaScript: The card's shadow tree
In real life: The fence
In JavaScript: The shadow boundary
In real life: Searching up to the fence
In JavaScript: document.querySelectorAll() and the other page searches
In real life: The neighbour searching their side
In JavaScript: Searches and closest() inside the card
In real life: Asking at the neighbour's gate
In JavaScript: Starting a search at card.shadowRoot on purpose

Try eight searches. Three start on the page, and five start at the card or inside it:

Playground: which searches cross the boundary?
Search from the page or from inside the cardPop out in the code editor (opens in a new tab)HTML
<p class="tea">Our teas</p><tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const name = card.shadowRoot.querySelector("p");  console.log(document.getElementsByTagName("p").length);</script>
ResultLoading…
Try it yourself
Line 8 prints 1

Only Our teas counts. getElementsByTagName() searches the page's own tree, like querySelectorAll(), so it stops at the card.

The page has one paragraph, Our teas. The card's shadow root has another, Green tea, with the same class (the tea-card.js tab). Line 7 keeps the card's paragraph in name. Each choice changes only line 8.

Here is what the eight searches show:

  • From the page, getElementsByTagName(), getElementsByClassName(), and contains() all stop at the card. The card's paragraph even has the same class, tea. It still isn't found.
  • From the shadow root, querySelectorAll() sees the card's tree only. Our teas, on the page, isn't counted.
  • A shadow root has no getElementsByTagName() or getElementsByClassName(). Documents and elements have them, and a shadow root is neither. The DOM Standard gives it getElementById(), querySelector(), and querySelectorAll().
  • closest() checks an element, then each of its parents in turn. It returns the first one that matches a selector. From inside, the climb ends at the shadow root, so closest("tea-card") gives null. Lesson 6.1 showed the same walk with parentElement: it gives null, while parentNode gives the shadow root.
Two halves. Left, a search from the page: p Our teas and tea-card are searched, and p Green tea, below the shadow boundary, is faded and crossed out. Under it: getElementsByTagName p finds 1 paragraph. Right, a search from inside the card: an arrow climbs from p Green tea and stops at the shadow boundary, so body and tea-card above it are faded and crossed out. Under it: closest tea-card gives null.a search from the page<p> Our teas<tea-card>shadow boundary<p> Green teagetElementsByTagName("p")finds 1 paragrapha search from inside the card<body><tea-card>shadow boundary<p> Green teaclosest("tea-card")gives null
Each search covers one tree. From the page, getElementsByTagName("p") never reaches Green tea. From inside, closest("tea-card") climbs to the shadow root and stops, so it gives null.

Why it matters: a component's searches can't grab the page's elements by mistake. And the page's searches can't grab the component's. Walking and searching the DOM covers these methods themselves.

Selectors inside a shadow root

matches() checks whether an element fits a selector. Inside the card, name.matches("tea-card p") is false. The selector wants a tea-card above the paragraph. In the paragraph's own tree, there isn't one.

The host does show up inside, but under one name only: :host. So name.matches(":host p") is true. A search from the root works the same way: card.shadowRoot.querySelector(":host p") finds Green tea. But card.shadowRoot.querySelector(":host") gives null, because the host isn't inside its own root. On the page, :host matches nothing at all.

Why so strict? The CSS Shadow spec explains. The host's tag and classes belong to the page author. If a component's rules could match them, a class on the page could clash with a class in the component. So inside its shadow tree, the host answers only to :host. The lesson on styling the host uses it.

Crossing on purpose

Encapsulation stops searches that wander across by accident. You can still cross on purpose:

  • A component searches its own parts from this.shadowRoot. The kit's card does this.
  • The page starts at card.shadowRoot when the root is open, as in lesson 6.1.
  • Code inside reaches the host with getRootNode().host. getRootNode() gives the shadow root, and its host is the card.

Searching every shadow root on a page at once is called a deep query. Lesson 9.4, Walking the composed tree, shows how.

How do ids work in shadow DOM?

Each shadow root keeps its own set of ids. An id only has to be unique inside one tree. That's how the first example held three elements with id="name". The CSS Shadow spec says it directly. An id can be used many times, "as long as each use is in a different shadow tree". A shadow root's own getElementById() looks in that root only.

Real-life analogyTable numbers in two cafés

Leaf and Kettle has a table 4. So does the café across the street. A waiter told to take tea to table 4 never crosses the road. And a note from the other café that says table 4 means nothing here.

In real life: Each café
In JavaScript: Each tree: the page, or one shadow root
In real life: Table 4 in both cafés
In JavaScript: id="name" in two trees
In real life: "Take this to table 4"
In JavaScript: An id reference, like for="cups"
In real life: The waiter stays in his own café
In JavaScript: A reference looks in its own tree only

That last pair matters most. Many attributes point at another element by its id. A <label for> points at its input. aria-labelledby and aria-describedby point at the text that names or describes an element. These are id references. MDN gives the rule: they can only refer to elements in the same DOM or shadow DOM.

References inside one root

Inside one shadow root, they all work. This card holds a small order form:

A label and a hint inside the card's shadow rootPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  const root = document.querySelector("tea-card").shadowRoot;  const cups = root.getElementById("cups");  console.log(cups.labels.length);  console.log(cups.labels[0].textContent);</script>
ResultLoading…
  • In the tea-card.js tab, line 6 is a label for cups. Line 7 is the input with that id. It also points at hint for its description. Line 8 is the hint.
  • On the page, line 6 finds the input through the root's own getElementById().
  • Line 7 prints 1. An input's labels lists the labels that belong to it.
  • Line 8 prints Cups.

Click Cups in the result, and the cursor jumps into the box. Now look at Chrome's accessibility tree for the card. The accessibility tree is the version of the page that screen readers use, as lesson 6.1 showed:

Chrome's accessibility tree for the order form (shortened)Text
RootWebArea
  generic
    LabelText
    spinbutton "Cups"
      description: "Up to 5 cups"
    paragraph

Line 4 is the input, a number box, which the accessibility tree calls a spinbutton. Its name is Cups, from the label. Its description is Up to 5 cups, from the hint. A screen reader reads both. Other id references work inside one root too, like the form, list, and popovertarget attributes, and SVG's url(#…) and <use href="#…">.

Why doesn't label for work across a shadow root?

Because a reference looks for its id in its own tree only. Pick a kind of reference. Each page points at one target inside the card, and one target across the boundary:

Playground: which id references reach?
One id reference inside the card, one acrossPop out in the code editor (opens in a new tab)HTML
<input id="page-cups" placeholder="Page cups"><tea-card></tea-card> <script src="tea-card.js"></script><script>  const root = document.querySelector("tea-card").shadowRoot;  const [inside, across] = root.querySelectorAll("label");  console.log("Inside the card:", inside.control !== null);  console.log("Across the boundary:", across.control !== null);</script>
ResultLoading…
Try it yourself
Inside the card: true. Across the boundary: false.

control is the input a label belongs to. The first label finds cups in its own root. The second looks for page-cups in the same root, finds nothing, and gets null. Click each label in the result: only Cups moves the cursor.

In the tea-card.js tab, line 6 is the target inside the card. Line 7 points at it, and line 8 points at the target on line 1 of the page. Each choice changes line 1, those three lines, and the tag and property on lines 7 to 9 of the page.

Every kind prints the same two lines: true inside, false across. The reference across the boundary doesn't throw an error. It quietly finds nothing. That makes these bugs easy to miss:

  • A label on the page doesn't label an input inside a component.
  • An input inside a component isn't sent with a form on the page.
  • aria-labelledby inside a component can't use text from the page. In Chrome's accessibility tree, the input simply has no name.
Two rows. Top row, inside one shadow root: label for cups points at input id cups, marked name: Cups. Bottom row, across the boundary: a window called page holds label for cups. Its arrow stops at the edge of a window called shadow root, which holds input id cups. Marked: control is null, no name.inside one shadow rootshadow root<label for="cups"><input id="cups">name: Cupsacross the boundarypage<label for="cups">shadow root<input id="cups">control is null, no name
Inside one shadow root, for="cups" finds the input, and the input gets the name Cups. A label on the page looks for cups in the page's tree only, so it finds nothing.

This is one of shadow DOM's real costs. Accessible components has a lesson on ARIA references across shadow roots, with the fixes. Until then, keep each label and its control in the same tree.

Links to an id inside a shadow root

A link like <a href="#steps"> normally scrolls to the element with id="steps". A target inside a shadow root never counts. The HTML Standard looks for it in the page's own tree only. In Chrome, a link inside a card to #steps in the same card changes the address. The page doesn't scroll.

Do styles leak in or out of shadow DOM?

No, in neither direction. Lesson 1.1 showed a page rule stopping at a card, and lesson 2.3 explained why. The other direction holds too. A component's rules never leak onto the page, not even very broad ones. Pick a rule, and see which paragraph it colors:

Playground: which rules reach?
One rule, on the page or in the cardPop out in the code editor (opens in a new tab)HTML
<style>  p { color: crimson; }</style><p>Page tea</p><tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `        <style>/* no rule here */</style>        <p>Card tea</p>`;    }  }  customElements.define("tea-card", TeaCard);</script>
ResultLoading…
Try it yourself
Page tea turns crimson

Page tea turns crimson. Card tea doesn't: the page's p selector can't pick a paragraph inside a shadow root.

Page tea is on the page. Card tea is in the card's shadow root. Each choice puts one rule on line 2, in the page's style, or on line 13, in the card's own style. The other line holds a comment.

Here is what the six rules show:

  • A selector only matches elements in the tree its style lives in. A page p rule colors Page tea. A card p rule colors Card tea.
  • Inside a shadow root, * means every element in that root, and nothing more. It doesn't even match the host.
  • body p inside the card matches nothing. The card's tree has no body.
  • Two rules color Card tea without selecting it at all: tea-card on the page, and :host inside the card. Both color the host, and the paragraph inherits the color.

Back at the market hall: the hall's display rules stop at each stall's counter. Each stall's own rules stop there too. Why it matters: a component can use short selectors like p and .card, and the page can too. Neither side can break the other's look by accident.

So what does reach into a shadow root? A short list, each with its own lesson in Styling web components:

  • Inherited properties, like color and font-family. Lesson 11.1, Styles inside a shadow root, shows how to reset them.
  • Custom properties, like --tea-accent. Lesson 2.3 used them, and lesson 12.1 turns them into a styling API.
  • ::part() rules, for elements a component names as parts. Lesson 2.3 met them too, and lesson 12.2 shows how a component names its parts.
  • And from inside, :host reaches out to the host element, and to nothing else.

Old guides also use /deep/, >>>, and ::shadow to reach into shadow roots. They were removed. Chrome throws a SyntaxError for them in querySelector(), and drops any CSS rule that uses them.

What crosses the shadow boundary?

Three things cross on purpose: inherited styles, events, and focus. They are how a component fits into its page. Each one gets a short look here, and a full lesson later.

Inherited styles, language, and direction

The page's color, font, and language reach the cardPop out in the code editor (opens in a new tab)HTML
<style>  body { color: saddlebrown; font-family: Georgia, serif; }</style><div lang="fr">  <tea-card></tea-card></div> <script src="tea-card.js"></script><script>  const name = document.querySelector("tea-card").shadowRoot.querySelector("p");  console.log(getComputedStyle(name).color);  console.log(name.matches(":lang(fr)"));</script>
ResultLoading…
  • Line 2 sets the page's text color and font on <body>.
  • Line 4 wraps the card in a <div> with lang="fr", for French.
  • In the tea-card.js tab, the card holds one paragraph: Thé vert, French for Green tea. It has no styles of its own.
  • Line 11 prints rgb(139, 69, 19). That's saddlebrown, the page's color.
  • Line 12 prints true. The paragraph counts as French.

The result shows Thé vert in saddlebrown, in Georgia. Inheritance doesn't follow the DOM tree here. It follows the flat tree: the tree the browser draws, where the shadow tree takes the place of the host's children. The CSS Shadow spec says CSS uses this tree for inheritance. So the paragraph inherits from the host, and the host from the page. MDN adds that lang and dir come from the host the same way.

Why it matters: a component matches the page's text with no work at all. Lesson 11.1, Styles inside a shadow root, shows how to stop it when you don't want that.

Events

A click inside the card, heard on the pagePop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("On the page:", event.target.localName);  });</script>
ResultLoading…
  • In the tea-card.js tab, line 5 puts a button in the shadow root. Line 6 listens for clicks inside the root. Line 7 prints what was clicked.
  • On the page, line 5 listens for clicks on the whole document. Line 6 prints the target.

Click Add Green tea. The console prints Inside: button, then On the page: tea-card. The click crossed the boundary, but the page sees the card, not the button. This change of target is called retargeting. It keeps the card's insides private, even in an event.

Clicks cross because they are composed. MDN says every UI event the browser dispatches is composed, and most other events aren't. Your own events cross only with composed: true, as lesson 5.3 showed. The lessons on event retargeting and composed events go deeper. Bubbling and capturing explains how events travel.

Focus

Focus inside the card, seen from the pagePop out in the code editor (opens in a new tab)HTML
<style>  tea-card:focus-within { outline: 3px solid seagreen; }</style><tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  card.addEventListener("focusin", () => {    console.log(document.activeElement.localName);    console.log(card.shadowRoot.activeElement.id);    console.log(card.matches(":focus"));  });</script>
ResultLoading…
  • Line 2 draws a sea green outline around the card while anything inside it has focus.
  • Line 9 listens for focusin, an event that fires when something inside gains focus.
  • Line 10 prints document.activeElement, the element the page thinks has focus.
  • Line 11 asks the shadow root instead.
  • Line 12 checks whether the card itself matches :focus.

Click in the Cups box. The console prints tea-card, cups, and true, and the card gets its outline. From the page, focus sits on the host. Only the shadow root knows which input has it. The HTML Standard says a host has focus, for :focus, when something in its shadow root does. So :focus and :focus-within both match the host. Lesson 9.3, Focus and shadow DOM, covers tab order and more. Keyboard and focus covers focus itself.

Real-life analogyCalls from an office show the main number

Leaf and Kettle's head office has twenty desks and one phone number. When Asha calls a supplier from her desk, the supplier's phone shows the main number. The supplier knows which company called. Only the office's own switchboard knows it was Asha's desk.

In real life: The head office
In JavaScript: The card
In real life: Asha's desk
In JavaScript: The button or input inside
In real life: The main number on the supplier's phone
In JavaScript: event.target and document.activeElement: the host
In real life: The office's own switchboard
In JavaScript: The shadow root: its listeners and shadowRoot.activeElement
A window called page holds the tea-card host. Below it, a window called shadow root holds a button and an input with id cups. On the left, an arrow points down from the page into the shadow root, labelled color, font-family, --tea-accent, and lang. On the right, an arrow points up from the shadow root to the page, labelled event.target and activeElement, which are the tea-card.page<tea-card>color, font-family--tea-accentlangevent.targetactiveElementare the tea-cardshadow root<button><input id="cups">
Inherited values flow down from the host into its shadow tree. Clicks and focus flow up, and on the page they show up as the host, <tea-card>.

Read each row across: what crosses, which way it goes, and what the other side sees.

What crosses the shadow boundary, and which way
What crossesWhich way?What the other side sees
Inherited properties, like color and font-familyInto the card.Elements inside inherit them from the host.
Custom properties, like --tea-accentInto the card.var(--tea-accent) inside reads the value the host has.
The lang and dir attributesInto the card.:lang() and :dir() inside match the host's language and direction.
::part() rulesInto the card.They style only the elements the card names with a part attribute.
:host rulesOut to the host.They style the host element from inside. Nothing else on the page matches.
Events the browser makes, like clickOut to the page.Page listeners see the host as event.target.
FocusOut to the page.document.activeElement is the host. shadowRoot.activeElement is the inner element.

Now sort what stops from what crosses:

Does it cross the shadow boundary?
  • document.getElementsByClassName("tea") finding the card's paragraph
  • name.closest("tea-card"), from a paragraph inside the card
  • A page <label for="cups"> and an input with id="cups" inside the card
  • The card's p { color: crimson; }, on the page's paragraphs
  • A link to #steps scrolling to id="steps" inside the card
  • body { color: saddlebrown; } on the page
  • --tea-accent: seagreen set on the page
  • lang="fr" on a parent of the card
  • A click on a button inside the card
  • Focus on an input inside the card
Try it yourself
0 of 10 correct

The card's shadow root holds a paragraph, a button, and an input. Sort each case by what happens.

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

How is shadow DOM different from an iframe?

An <iframe> also keeps things apart. It's much stronger, and much heavier. Here are the two side by side:

A shadow root next to an iframePop out in the code editor (opens in a new tab)HTML
<style>  body { color: saddlebrown; }</style><tea-card></tea-card><iframe srcdoc="<p>Oolong, in an iframe</p>"></iframe> <script src="tea-card.js"></script><script>  document.addEventListener("click", (event) => {    console.log("The page heard a click on", event.target.localName);  });</script>
ResultLoading…
  • Line 2 colors the page's text saddlebrown.
  • Line 4 is a card with a shadow root. Line 5 is an iframe. Its srcdoc attribute holds a whole small page.
  • Lines 9 to 11 print every click the page hears.

In the result, Green tea is saddlebrown, and Oolong isn't. Click each one. Green tea prints The page heard a click on tea-card. Oolong prints nothing. The page's color doesn't go into the iframe, and the iframe's clicks stay inside it.

An iframe holds a separate document. MDN calls it a nested browsing context. It has its own window, its own globals, and its own CSS, from scratch. A shadow root shares the page's document and window. It only scopes names, styles, and searches. That strength costs the iframe a lot:

  • Memory. MDN warns that each iframe is a complete document environment. So every one needs more memory and other resources.
  • Size. An iframe doesn't grow to fit what's inside. With no size set, Chrome draws this one 300 by 150 pixels, plus its border.
  • Talking. A page can't reach into an iframe from another origin. The two sides send messages with postMessage().
Real-life analogyA stall in the hall, or a shop of its own

A tea seller can rent a stall in the market hall, or a shop across the road. The stall shares the hall's light, doors, and customers. The shop has its own door, lights, and bills. It's more private, but every visit means a walk across the road.

In real life: A stall in the market hall
In JavaScript: A shadow root: the same document and window
In real life: The hall's light reaching the stall
In JavaScript: Inherited styles crossing in
In real life: A shop of its own across the road
In JavaScript: An iframe: a separate document
In real life: Its own lights and its own bills
In JavaScript: Its own window and CSS, and the memory they cost
In real life: Walking across the road to talk
In JavaScript: postMessage() between a page and a cross-origin iframe

A component should look and act like part of the page: the same fonts, the same events, the same focus. So shadow DOM is the tool for components. An iframe fits content from another site that the page must not touch.

Is encapsulation a security feature?

No. The CSS Shadow spec says shadow DOM is "intentionally not a security boundary, merely a convenience for page authors". Lesson 6.2 showed scripts getting into even a closed root. Encapsulation protects code from accidents: a stray selector, a clashing id, a search that wanders too far. It doesn't protect secrets.

What it does protect is change. Nolan Lawson puts it this way. When page styles can't reach inside, a component's author offers a clear styling API instead. Then the author can change the insides in the next version without breaking the pages that use it.

Giving the tea card ids of its own

Back to Asha's menu. The kit's tea card from lesson 6.1 finds its heading with querySelector("h3"). That works, but the card's box has no name for screen readers. Now that ids are safe inside a root, the card can use them. Here is the menu with the kit's new card:

Two kit cards and a page heading, all with id namePop out in the code editor (opens in a new tab)HTML
<h2 id="name">Our teas</h2><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";   for (const card of document.querySelectorAll("tea-card")) {    console.log(card.shadowRoot.getElementById("name").textContent);  }</script>
ResultLoading…
  • Line 1 is the page's heading. It uses id="name" too.
  • Lines 2 and 3 are two cards.
  • Line 6 loads the whole kit.
  • Lines 8 to 10 ask each card's root for its name. They print Green tea and Oolong.

Here is the card's new file, tea-kit/tea-card.js. It's also one of the tabs above:

The kit's tea card, with ids inside its rootJavaScript
/**
 * A tea card: a tea's name and price in a box. Its own shadow root holds the box and its styles.
 *
 * @tag tea-card
 * @attr {string} name - The tea's name.
 * @attr {string} price - The tea's price.
 */
export class TeaCard extends HTMLElement {
  static observedAttributes = ["name", "price"];

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
      <style>
        .card { border: 2px solid seagreen; border-radius: 8px; padding: 8px 12px; }
        h3 { margin: 0; color: seagreen; }
        p { margin: 4px 0 0; }
      </style>
      <article class="card" aria-labelledby="name">
        <h3 id="name"></h3>
        <p id="price"></p>
      </article>`;
  }

  attributeChangedCallback(name, oldValue, newValue) {
    const text = newValue ?? "";
    if (name === "name") this.shadowRoot.getElementById("name").textContent = text;
    if (name === "price") this.shadowRoot.getElementById("price").textContent = `Price: ${text}`;
  }
}

customElements.define("tea-card", TeaCard);
  • Line 20 makes the box an <article>. MDN lists a product card as one use of it. Its aria-labelledby="name" names the box after its heading.
  • Line 21 gives the heading id="name". Line 22 gives the price line id="price".
  • Lines 28 and 29 find them with this.shadowRoot.getElementById().
  • The rest is as lesson 6.1 left it.

Chrome's accessibility tree shows what changed:

Chrome's accessibility tree for the menu (shortened)Text
RootWebArea
  heading "Our teas"
  article "Green tea"
    heading "Green tea"
    paragraph
  article "Oolong"
    heading "Oolong"
    paragraph

Lines 3 and 6 are the two cards. Each is an article named after its own tea. Three elements on this page have id="name", and each reference found the right one. Ravi picked short, plain ids, and no page can break them. That's encapsulation doing its job.

Common mix-ups

  • "Ids must be unique across every component on the page." No. Ids only need to be unique inside one tree. Each shadow root is its own tree, so every card can use id="name".
  • "No page CSS reaches a shadow root." No. Inherited properties like color and font-family, custom properties, and ::part() rules all reach in.
  • "A component's broad rules, like * or body, can leak onto the page." No. Rules inside a shadow root only match elements in that root. * stops there, and body matches nothing.
  • "Shadow DOM stops events." No. Composed events, like every click, cross the boundary. Outside, their target is the host.
  • "A page label can point at an input inside a component." No. Id references look in their own tree only. The label's control is null, and the input gets no name.
  • "You can still reach inside with /deep/, >>>, or ::shadow." No. They were removed. Chrome throws a SyntaxError for them in querySelector() and drops CSS rules that use them.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upClimb from inside

What do lines 7 and 8 print?

<tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const name = card.shadowRoot.querySelector("p");  console.log(name.closest("div").className);  console.log(name.closest("tea-card"));</script>
ResultLoading…

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

    Exercise 2 · Warm-upWhich color does the page keep?

    The card's style turns crimson anything called body or p. What does the page print?

    <style>  body { color: saddlebrown; }</style><p>Page tea</p><tea-card></tea-card> <script src="tea-card.js"></script><script>  const page = document.querySelector("p");  console.log(getComputedStyle(page).color);</script>
    ResultLoading…

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

      Exercise 3 · PracticeFind the bug

      The card stays empty, and the console shows an error. Which error, and how do you fix it?

      <tea-card price="4"></tea-card> <script src="tea-card.js"></script>
      ResultLoading…

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

        Exercise 4 · PracticeLabel the input

        The page prints 0: the input has no label. Make the label belong to the input. What does the page print then?

        <label for="cups">Cups</label><tea-card></tea-card> <script src="tea-card.js"></script><script>  const cups = document.querySelector("tea-card").shadowRoot.getElementById("cups");  console.log(cups.labels.length);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeColor the card from the page

          Write one rule on line 2 that turns Green tea sea green and leaves Our teas alone. Don't change tea-card.js. What does the page print?

          <style>  /* Add one rule here. Don't change tea-card.js. */</style><p>Our teas</p><tea-card></tea-card> <script src="tea-card.js"></script><script>  const name = document.querySelector("tea-card").shadowRoot.querySelector("p");  console.log(getComputedStyle(name).color);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeCount every paragraph

            Write countParagraphs() so it counts the page's paragraphs and the ones inside every card. What does it return?

            <p>Our teas</p><tea-card></tea-card><tea-card></tea-card> <script src="tea-card.js"></script><script>  function countParagraphs() {    // Count the page's paragraphs,    // plus the ones inside each card's shadow root.  }  console.log(countParagraphs());</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask which tree the code runs in, and which tree it's looking at.

              The encapsulation quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A paragraph sits inside a tea card's shadow root. What does name.closest("tea-card") give?

                Choose an answer to see the explanation.

              2. Question 2 of 7A page has <h3 id="name"> and two tea cards, each with <h3 id="name"> in its shadow root. What is document.querySelectorAll("#name").length?

                Choose an answer to see the explanation.

              3. Question 3 of 7In the rule playground with * { color: crimson; } inside the card, which paragraphs turn crimson?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  /* no rule here */
                </style>
                <p>Page tea</p>
                <tea-card></tea-card>
                
                <script>
                  class TeaCard extends HTMLElement {
                    constructor() {
                      super();
                      this.attachShadow({ mode: "open" });
                      this.shadowRoot.innerHTML = `
                        <style>* { color: crimson; }</style>
                        <p>Card tea</p>`;
                    }
                  }
                  customElements.define("tea-card", TeaCard);
                </script>

                Choose an answer to see the explanation.

              4. Question 4 of 7A page has <label for="cups">Cups</label>, and a card has <input id="cups"> in its shadow root. What happens when you click the label?

                Choose an answer to see the explanation.

              5. Question 5 of 7Someone clicks a button inside a tea card's shadow root. What is event.target for a click listener on document?

                Choose an answer to see the explanation.

              6. Question 6 of 7The cursor is in an input inside a tea card. What is document.activeElement?

                Choose an answer to see the explanation.

              7. Question 7 of 7How is a shadow root different from an <iframe>?

                Choose an answer to see the explanation.

              Key takeaways

              • Encapsulation means scoping. A shadow root keeps its own ids, CSS rules, and searches.
              • Searches stop at the boundary both ways. Page searches can't see in, and closest() from inside stops at the root. A shadow root has querySelector() and getElementById(), but no getElementsByTagName().
              • Each shadow root is its own id scope. for, aria-labelledby, form, list, and popovertarget work inside one root and quietly fail across it.
              • Page rules don't reach in, and a component's rules don't leak out, not even *. Inside, the host answers only to :host.
              • Inherited properties, custom properties, lang, and ::part() cross in. Clicks and focus cross out, as the host.
              • It isn't security, and it isn't an iframe. An iframe holds a whole separate document, at a cost.

              Remember the one-liner.
              A shadow root is a scope: its names, styles, and searches stay inside, and inherited styles, events, and focus cross.

              Sources

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

              Coming next: When to skip shadow DOM, the next lesson in this stage. Scoped ids and styles have costs, as this lesson showed. When is light DOM the better choice?

              CompleteFrontend Clear concepts. Working examples.