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.
- 01Say 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.
- 02Use ids safely inside a componentGive a component short ids of its own, and spot the references, like
<label for>, that can't cross. - 03Know 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:
<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>- 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.jstab. - In that tab, line 6 gives the card an
h3rule of its own: sea green. Line 7 is the card's heading. Its id isnametoo. Line 10 writes the card'snameattribute into it. - Back on the page, line 11 counts the elements with the id
namethat the page can find. It prints1. - Lines 12 and 13 ask each card's shadow root for its own
name. They printGreen teaandOolong.
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.
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.
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
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().
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.shadowRooton purpose
Try eight searches. Three start on the page, and five start at the card or inside it:
<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>Only Our teas counts. getElementsByTagName() searches the page's own tree, like querySelectorAll(), so it stops at the card.
Here is what the eight searches show:
- From the page,
getElementsByTagName(),getElementsByClassName(), andcontains()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()orgetElementsByClassName(). Documents and elements have them, and a shadow root is neither. The DOM Standard gives itgetElementById(),querySelector(), andquerySelectorAll(). 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, soclosest("tea-card")givesnull. Lesson 6.1 showed the same walk withparentElement: it givesnull, whileparentNodegives the shadow root.
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.shadowRootwhen the root is open, as in lesson 6.1. - Code inside reaches the host with
getRootNode().host.getRootNode()gives the shadow root, and itshostis 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.
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:
<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>- In the
tea-card.jstab, line 6 is a label forcups. Line 7 is the input with that id. It also points athintfor 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'slabelslists 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:
RootWebArea
generic
LabelText
spinbutton "Cups"
description: "Up to 5 cups"
paragraphLine 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:
<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>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.
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-labelledbyinside a component can't use text from the page. In Chrome's accessibility tree, the input simply has no name.
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:
<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>Page tea turns crimson. Card tea doesn't: the page's p selector can't pick a paragraph inside a shadow root.
Here is what the six rules show:
- A selector only matches elements in the tree its style lives in. A page
prule colors Page tea. A cardprule colors Card tea. - Inside a shadow root,
*means every element in that root, and nothing more. It doesn't even match the host. body pinside the card matches nothing. The card's tree has nobody.- Two rules color Card tea without selecting it at all:
tea-cardon the page, and:hostinside 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
colorandfont-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,
:hostreaches 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
<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>- Line 2 sets the page's text color and font on
<body>. - Line 4 wraps the card in a
<div>withlang="fr", for French. - In the
tea-card.jstab, 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
<tea-card></tea-card> <script src="tea-card.js"></script><script> document.addEventListener("click", (event) => { console.log("On the page:", event.target.localName); });</script>- In the
tea-card.jstab, 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
<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>- 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.
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.targetanddocument.activeElement: the host - In real life: The office's own switchboard
- In JavaScript: The shadow root: its listeners and
shadowRoot.activeElement
<tea-card>.Read each row across: what crosses, which way it goes, and what the other side sees.
| What crosses | Which way? | What the other side sees |
|---|---|---|
Inherited properties, like color and font-family | Into the card. | Elements inside inherit them from the host. |
Custom properties, like --tea-accent | Into the card. | var(--tea-accent) inside reads the value the host has. |
The lang and dir attributes | Into the card. | :lang() and :dir() inside match the host's language and direction. |
::part() rules | Into the card. | They style only the elements the card names with a part attribute. |
:host rules | Out to the host. | They style the host element from inside. Nothing else on the page matches. |
Events the browser makes, like click | Out to the page. | Page listeners see the host as event.target. |
| Focus | Out to the page. | document.activeElement is the host. shadowRoot.activeElement is the inner element. |
Now sort what stops from what crosses:
document.getElementsByClassName("tea")finding the card's paragraphname.closest("tea-card"), from a paragraph inside the card- A page
<label for="cups">and an input withid="cups"inside the card - The card's
p { color: crimson; }, on the page's paragraphs - A link to
#stepsscrolling toid="steps"inside the card body { color: saddlebrown; }on the page--tea-accent: seagreenset on the pagelang="fr"on a parent of the card- A click on a button inside the card
- Focus on an input inside the card
The card's shadow root holds a paragraph, a button, and an input. Sort each case by what happens.
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:
<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>- Line 2 colors the page's text saddlebrown.
- Line 4 is a card with a shadow root. Line 5 is an iframe. Its
srcdocattribute 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().
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:
<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>- 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 printGreen teaandOolong.
Here is the card's new file, tea-kit/tea-card.js. It's also one of the tabs above:
/**
* 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. Itsaria-labelledby="name"names the box after its heading. - Line 21 gives the heading
id="name". Line 22 gives the price lineid="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:
RootWebArea
heading "Our teas"
article "Green tea"
heading "Green tea"
paragraph
article "Oolong"
heading "Oolong"
paragraphLines 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
colorandfont-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, andbodymatches 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
controlisnull, and the input gets no name. - "You can still reach inside with /deep/, >>>, or ::shadow." No. They were removed. Chrome throws a
SyntaxErrorfor them inquerySelector()and drops CSS rules that use them.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
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>card, then null. The div is in the same shadow tree as the paragraph, so closest() finds it. The card is outside that tree.
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>rgb(139, 69, 19), which is saddlebrown. The card's body, p rule only colors Card tea. Page tea keeps the color from the page's own body rule.
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><tea-card price="4"></tea-card> <script src="tea-card.js"></script>A TypeError: Cannot set properties of null (setting 'textContent'). document.getElementById() can't see into the shadow root, so it gives null. Searching from this.shadowRoot finds the line, and the card shows Price: 4.
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><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>It prints 1. The label and the input are now in the same tree, so the reference finds the input. Clicking Cups moves the cursor into the box.
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><style> tea-card { color: seagreen; }</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>It prints rgb(46, 139, 87), which is seagreen. The rule colors the host, and the card's paragraph inherits from the host. Our teas keeps its color.
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><p>Our teas</p><tea-card></tea-card><tea-card></tea-card> <script src="tea-card.js"></script><script> function countParagraphs() { let count = document.querySelectorAll("p").length; for (const card of document.querySelectorAll("tea-card")) { count += card.shadowRoot.querySelectorAll("p").length; } return count; } console.log(countParagraphs());</script>It prints 5: one paragraph on the page, and two inside each card. The loop crosses on purpose, one shadow root at a time.
Check your understanding
For each question, ask which tree the code runs in, and which tree it's looking at.
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.
Question 2 of 7A page has
<h3 id="name">and two tea cards, each with<h3 id="name">in its shadow root. What isdocument.querySelectorAll("#name").length?Choose an answer to see the explanation.
Question 3 of 7In the rule playground with
* { color: crimson; }inside the card, which paragraphs turn crimson?Read the code, then predict<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.
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.
Question 5 of 7Someone clicks a button inside a tea card's shadow root. What is
event.targetfor a click listener ondocument?Choose an answer to see the explanation.
Question 6 of 7The cursor is in an input inside a tea card. What is
document.activeElement?Choose an answer to see the explanation.
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 hasquerySelector()andgetElementById(), but nogetElementsByTagName(). - Each shadow root is its own id scope.
for,aria-labelledby,form,list, andpopovertargetwork 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:
- Using shadow DOM: encapsulation from JavaScript and from CSS, MDN.
- CSS Shadow Module Level 1: Shadow DOM and Selectors, W3C CSS Working Group.
- DOM Standard: closest() and contains(), WHATWG.
- DOM Standard: Interface DocumentFragment, WHATWG.
- CSS Shadow Module Level 1: Name-Defining Constructs and Inheritance, W3C CSS Working Group.
- Attribute reflection: Element id reference scope, MDN.
- HTML Standard: find a potential indicated element, WHATWG.
- CSS Shadow Module Level 1: Flattening the DOM into an Element Tree, W3C CSS Working Group.
- Using shadow DOM: attribute inheritance, MDN.
- Event: composed, MDN.
- ShadowRoot: activeElement, MDN.
- HTML Standard: the :focus pseudo-class, WHATWG.
- <iframe>: The Inline Frame element, MDN.
- CSS Shadow Module Level 1: Security Considerations, W3C CSS Working Group.
- Shadow DOM and the problem of encapsulation, Nolan Lawson.
- <article>: The Article Contents element, MDN.
- CSS Shadow Module Level 1: Changes, W3C CSS Working Group.
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?