Open and closed shadow roots
Open vs closed shadow DOM: why closed mode makes element.shadowRoot null, how a component still reaches its own root, and why closed isn't a security feature.
- 01Say what closed mode changesClosed mode hides
shadowRoot, part ofcomposedPath(), andassignedSlotfrom outside code. Drawing, styles, and events stay the same. - 02Reach your own closed rootKeep what
attachShadow()returns, climb withgetRootNode(), or readattachInternals().shadowRoot, even for a root written in HTML. - 03Explain why closed isn't a lockShow how other code on the page still gets in, and choose open unless you have a clear reason not to.
What is the difference between open and closed shadow DOM?
Ravi's tea card from lesson 6.1 is popular. A partner café now shows it on their own website. Last week, their developer wanted a sale. He reached into the card through card.shadowRoot and changed the price. Lesson 6.1 showed that any script can do that.
Ravi reads about a fix. Change one word: mode: "open" becomes mode: "closed". He tries it, and card.shadowRoot gives null. Is the card safe now? And what else did that one word change?
In open mode, element.shadowRoot gives any script the shadow root. In closed mode, it gives null. That's nearly the whole difference. The component still keeps its root. The browser still draws it. And code that's trying can still get in. So closed mode is a sign that says "please don't touch". It isn't a lock.
The mode you pass to attachShadow() picks one or the other. Here are both, side by side:
<div id="open"></div><div id="closed"></div> <script> const open = document.querySelector("#open"); const closed = document.querySelector("#closed"); const openRoot = open.attachShadow({ mode: "open" }); const closedRoot = closed.attachShadow({ mode: "closed" }); openRoot.innerHTML = "<p>Green tea, in an open root</p>"; closedRoot.innerHTML = "<p>Black tea, in a closed root</p>"; console.log(open.shadowRoot === openRoot); console.log(closed.shadowRoot);</script>- Lines 1 and 2 are two empty divs.
- Line 7 gives the first div an open shadow root. Line 8 gives the second div a closed one. Each call returns the new root, and the code keeps it in a variable.
- Lines 9 and 10 fill both roots. Line 10 works fine:
closedRootstill leads to the closed root. - Line 12 prints
true. The open div'sshadowRootis the same root asopenRoot. - Line 13 prints
null. The closed div won't hand out its root.
The result shows both teas. A closed root is drawn like any other. Only one way in went away: the shadowRoot property.
shadowRoot leads to the root. For the closed div, it gives null. The closed root still exists, and the variable closedRoot from line 8 still leads to it.Leaf and Kettle keeps its tea in a cupboard. For years, the key hung on a hook by the till. Anyone could take it. Then the manager started keeping the key in her pocket. The hook is empty now. The cupboard and the tea inside didn't change at all.
- In real life: The hook by the till
- In JavaScript:
element.shadowRoot, which any script can read - In real life: The key on the hook
- In JavaScript: An open root:
shadowRootgives it - In real life: The empty hook
- In JavaScript: A closed root:
shadowRootgivesnull - In real life: The key in the manager's pocket
- In JavaScript: The root the code kept from
attachShadow() - In real life: The cupboard and the tea inside
- In JavaScript: The shadow tree, drawn and styled as before
mode decides one thing: whether element.shadowRoot hands out the root. "open" gives the root to any script. "closed" gives null. attachShadow() returns the root either way, so the component keeps it. Closed mode is a polite sign, not a lock.
What does closed mode change?
Three things change. All three are about what code outside the root can see:
element.shadowRootgivesnull.- An event's
composedPath(), read outside the root, leaves out the nodes inside it. - A slotted child's
assignedSlotgivesnull. You'll meet slots later in this stage.
For the last two, the DOM Standard uses one rule. It calls it closed-shadow-hidden. A node is hidden from your code when it lives in a closed shadow root and you're asking from outside that root. Code inside the root sees everything, as before.
Keeping the root in a private field
So how does Ravi's card fill and update its closed root? The same way the first example did. It keeps what attachShadow() returns. A class keeps it in a field. Here is the card in its own file, tea-card.js. Click the second tab to see it:
<tea-card price="4"></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); console.log(card.shadowRoot); card.setAttribute("price", "5");</script>Start in the tea-card.js tab:
- Line 3 declares
#root. The#makes it a private field: only code inside the class can read it. Private fields and methods covers them. - Line 7 attaches a closed root and keeps it in
#root. - Line 8 fills it with the tea's name and a price line.
- Line 12 runs each time
pricechanges. The selectorp + pmeans a paragraph right after another one. So it finds the price line, through#root.
Then the page, in the first tab:
- Line 6 prints
null. The page can't get the root. - Line 7 sets the
priceattribute to 5. The result shows Price: 5.
The card still works fully. The page talks to it through its attribute, the way a component's users should. But the partner café's line now fails. card.shadowRoot.querySelector("p") throws TypeError: Cannot read properties of null (reading 'querySelector'). Their code can't treat null as a root.
One rule follows from this. With a closed root, the class must keep its own reference. If it forgets, this.shadowRoot gives the class null too. Exercise 3 has that bug.
Do you have to pass a mode?
Yes. mode has no default. Call attachShadow({}) without it, and Chrome throws a TypeError. The message says the mode is a Required member. So every shadow root is open or closed on purpose.
Which nodes does composedPath() show?
event.composedPath() lists the nodes an event passes through. It starts at the node where the event began, and goes up to window. Lesson 5.3 showed retargeting: outside a shadow root, event.target becomes the host. Does closed mode change that? Pick a mode, then click the card in the result:
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachShadow({ mode: "open" }); root.innerHTML = "<p>Click me: Green tea</p>"; root.addEventListener("click", (event) => { console.log("Inside, the path starts at", event.composedPath()[0].localName); }); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); console.log("card.shadowRoot is", card.shadowRoot ? "a ShadowRoot" : "null"); document.addEventListener("click", (event) => { console.log("The page sees the target", event.target.localName); console.log("The page's path starts at", event.composedPath()[0].localName); });</script>The page can reach the root through card.shadowRoot. After a click, the page's event.target is the card. But its composedPath() still starts at the paragraph inside.
- Line 10 runs inside the root. It prints where the path starts.
- Line 17 prints whether the page got the root through
card.shadowRoot. - Lines 19 and 20 run on the page, after the click.
In both modes, line 19 says the target is tea-card. Retargeting doesn't care about the mode. The difference is line 20. With an open root, the page's path starts at the paragraph, p. With a closed root, it starts at tea-card. Inside the root, line 10 says p either way.
composedPath() starts at the paragraph. On the page, it leaves out the paragraph and the shadow root, and starts at tea-card.So the page can't use composedPath() to peek into a closed root. Code inside the root still sees the whole path. That's how a component handles clicks on its own buttons.
What stays the same in closed mode?
Everything that isn't about scripts reaching in. Lesson 6.1 listed what shadow DOM doesn't hide. Closed mode keeps that list as it is:
- A closed root is drawn, as the first example showed.
- Inherited styles, custom properties, and
::part()still reach in. - Events still cross out, with the host as their target, as the playground showed.
- Screen readers read it, and find in page finds its text.
- Focus works the same. Tab to a button inside, and
document.activeElementis the host in both modes.
Here the page styles a closed card from outside:
<style> tea-card { color: seagreen; --tea-accent: seagreen; } tea-card::part(name) { text-decoration: underline; } p { color: crimson; }</style> <tea-card></tea-card> <script src="tea-card.js"></script>- Line 2 sets the card's text color and a custom property,
--tea-accent. - Line 3 styles the part called
name. In thetea-card.jstab, line 8 gives the first paragraphpart="name". Lesson 2.3 showed parts. - Line 4 tries to turn every paragraph crimson.
The result shows Green tea underlined. Both lines are sea green, and the price has a sea green border. Line 4 changes nothing inside the card. The same rules reach in as with an open root, and the same rules stop.
A new waiter at Leaf and Kettle turns his name tag around. Customers can't read his name any more. But he still takes orders, carries trays, and calls out when the tea is ready. Nothing about his work changed. One label went out of view.
- In real life: The name tag
- In JavaScript:
element.shadowRoot - In real life: Turning it around
- In JavaScript:
mode: "closed" - In real life: He still takes orders and carries trays
- In JavaScript: The root is still drawn, styled, and read aloud
- In real life: Customers still hear him call out
- In JavaScript: Events still cross out to the page
Open and closed, side by side
Read each row across: what you check, then what you get with each mode.
| What you check | With an open root | With a closed root |
|---|---|---|
What attachShadow() returns | The new shadow root. | The new shadow root. |
element.shadowRoot from any script | The shadow root. | null. |
composedPath() in a page listener | It starts at the node that was clicked. | It starts at the host. |
event.target in a page listener | The host. | The host. |
A slotted child's assignedSlot | The slot it shows in. | null. |
Inherited styles, custom properties, and ::part() | They reach in. | They reach in. |
| Drawing, screen readers, and find in page | They all work. | They all work. |
| DevTools' Elements panel | It shows #shadow-root (open). | It shows #shadow-root (closed). |
| Playwright locators | They find nodes inside. | They find nothing inside. |
Closed roots in DevTools
DevTools isn't a script on the page, so it sees closed roots. Chrome's Elements panel shows the styled card like this:
<tea-card>
#shadow-root (closed)
<p part="name">Green tea</p>
<p style="border: 2px solid var(--tea-accent)">Price: 4</p>
</tea-card>Line 2 is the closed root. Lines 3 and 4 are inside it. You can open it, read it, and change it there, like an open one. DevTools builds the label from the root's type, as its own source shows. An open root reads #shadow-root (open).
Why is element.shadowRoot null?
A closed root is one reason. There are three more, and they cause common bugs:
<tea-card></tea-card><video controls width="200"></video><div></div> <script> const card = document.querySelector("tea-card"); console.log(card.shadowRoot); class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } } customElements.define("tea-card", TeaCard); console.log(card.shadowRoot.mode); console.log(document.querySelector("video").shadowRoot); console.log(document.querySelector("div").shadowRoot);</script>- Line 7 prints
null. The page reads the card before its class is defined. The card hasn't upgraded yet, so it has no shadow root at all. Lesson 4.1 covers upgrades. - Line 15 defines the class, and the card upgrades. Its constructor attaches an open root.
- Line 16 prints
open. The same card has its root now. - Line 18 prints
null. A video's shadow root belongs to the browser, as lesson 6.1 showed. - Line 19 prints
null. Nothing ever gave this div a shadow root.
So when you see null, ask four questions:
- Is the root closed?
- Has the element's class been defined yet?
- Is it a built-in element, like
<input>or<video>? - Did anything call
attachShadow()on it at all?
Why does a video give null too? Chrome keeps every shadow root the same way. It checks the mode only when a script reads shadowRoot, and its getter hands out open roots only. The browser's own roots aren't open. So to scripts, they act like closed ones.
Finding the root again from inside
Code inside a closed root doesn't need a field. Any node can climb to its root with getRootNode(), which lesson 6.1 showed:
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachShadow({ mode: "closed" }); root.innerHTML = "<p>Green tea</p><button>Add to order</button>"; root.querySelector("button").addEventListener("click", (event) => { const sameRoot = event.currentTarget.getRootNode(); sameRoot.querySelector("p").textContent = "Green tea: added"; console.log(sameRoot.mode); }); } } customElements.define("tea-card", TeaCard);</script>- Line 7 attaches a closed root. Only a local variable,
root, holds it. - Line 9 listens for clicks on the button.
- Line 10 climbs from the button to its root.
event.currentTargetis the element the listener sits on, the button. - Line 11 changes the paragraph. Line 12 prints
closed.
Press Add to order in the result. It shows Green tea: added, and the console prints closed. This has a second side. Any inner node a component hands out leads back to its root. Put one in an event's detail, and the page can call getRootNode() on it too.
A closed root written in HTML
A shadow root can also come from HTML, with no script. Lesson 1.2 showed one. The shadowrootmode attribute sets its mode:
<tea-card> <template shadowrootmode="closed"> <p>Green tea</p> </template></tea-card> <script> const card = document.querySelector("tea-card"); console.log(card.shadowRoot); console.log(card.children.length);</script>- Lines 2 to 4 are a
<template>withshadowrootmode="closed". The browser turns it into a closed shadow root while it reads the HTML. - Line 9 prints
null. The root is closed. - Line 10 prints
0. The template is gone. It became the root, not a child.
The result shows Green tea. The lesson on declarative shadow DOM, in Server rendering, covers roots written in HTML in full. Here, they raise a question. No code called attachShadow(), so no code kept the root. How does the card's class reach it?
How does a component reach its own closed shadow root?
There are three ways, all from inside the class:
- Keep what
attachShadow()returns, in a private field like#root. - Call
getRootNode()on any node inside the root. - Ask the element's internals:
this.attachInternals().shadowRoot.
The first two only work if the class made the root, or holds a node in it. The third also works for a root built from HTML. ElementInternals is an object each custom element can ask for once, with attachInternals(). Lesson 5.7 met it: it's how a component joins forms and sets its own role. It can also give the component its shadow root.
<tea-card price="4"> <template shadowrootmode="closed"> <p>Green tea</p> <p class="price"></p> </template></tea-card> <script> class TeaCard extends HTMLElement { static observedAttributes = ["price"]; #root; constructor() { super(); this.#root = this.attachInternals().shadowRoot; if (!this.#root) { this.#root = this.attachShadow({ mode: "closed" }); this.#root.innerHTML = '<p>Green tea</p><p class="price"></p>'; } console.log(this.shadowRoot, this.#root.mode); } attributeChangedCallback(name, oldValue, newValue) { this.#root.querySelector(".price").textContent = `Price: ${newValue}`; } } customElements.define("tea-card", TeaCard);</script>- Lines 2 to 5 write a closed root in the HTML, with the tea's name and an empty price line.
- Line 15 asks for the card's internals and reads their
shadowRoot. The browser built the root before the class ran, and the internals hand it over. - Lines 16 to 19 run only when there's no root yet. Then the class attaches its own and fills it. So the class works with or without a root in the HTML.
- Line 20 prints
null closed.this.shadowRootisnull, but#rootholds the closed root. - Line 24 fills in the price. The result shows Green tea and Price: 4.
Press Edit & run, delete lines 2 to 5, and run it again. Now there's no root in the HTML, so the class attaches its own. The result looks the same.
A parcel arrives while you're out. The courier takes it to the post office and leaves a slip at your door. You take the slip to the counter, and the clerk hands you the parcel. Each parcel is handed over once.
- In real life: The parcel that came while you were out
- In JavaScript: The root the browser built from the HTML
- In real life: Your empty doorstep
- In JavaScript:
this.shadowRoot, which isnullfor a closed root - In real life: The post office counter
- In JavaScript:
this.attachInternals() - In real life: The clerk handing you the parcel
- In JavaScript:
internals.shadowRoot - In real life: Each parcel is handed over once
- In JavaScript: A second
attachInternals()call throws
card.shadowRoot gives null. The class asks for its internals, and internals.shadowRoot leads to the root.How the browser decides
The HTML Standard spells out what reading internals.shadowRoot does. In plain words:
- Take the element these internals belong to.
- If it has no shadow root, give
null. - If its root isn't marked as available to the element's internals, give
null. - Otherwise, give the root, open or closed.
So the mode never matters here. The mark does. The DOM Standard and the HTML parser set it in two cases:
- The element was a custom element, or was being made into one, when
attachShadow()ran. Its constructor counts. - The browser built the root from HTML.
A root that other code attached before the upgrade doesn't get the mark. Try all four cases:
<tea-card></tea-card> <script> const card = document.querySelector("tea-card"); // The page leaves the card alone. class TeaCard extends HTMLElement { constructor() { super(); const internals = this.attachInternals(); this.attachShadow({ mode: "open" }).innerHTML = "<p>Green tea</p>"; console.log("internals.shadowRoot:", internals.shadowRoot?.mode ?? null); } } customElements.define("tea-card", TeaCard);</script>The constructor attached the root, so the class can reach it through its internals. This works for an open root too, not only a closed one.
Three choices print a mode. Closed, by the page first prints null. The page made that root before the card was a custom element, so the class doesn't get it. And open roots work too. The internals aren't only for closed roots.
Is a closed shadow root secure?
No. MDN says you "should not consider this a strong security mechanism". It's "more of an indication" that the page shouldn't reach in. Here are three ways other code gets in anyway.
Wrapping attachShadow before the component loads
Every component calls Element.prototype.attachShadow. A page script can swap that method for its own function first. Then it sees every root the page makes:
<script> const kept = []; const attach = Element.prototype.attachShadow; Element.prototype.attachShadow = function (options) { const root = attach.call(this, options); kept.push(root); return root; };</script> <tea-card price="4"></tea-card><script src="tea-card.js"></script><script> console.log(document.querySelector("tea-card").shadowRoot); const name = kept[0].querySelector("p"); console.log(kept[0].mode, name.textContent); name.textContent = "Free tea";</script>- Line 2 makes an empty array,
kept. - Line 3 saves the real method.
- Lines 4 to 8 replace it. Line 5 calls the real method, for the same element and options.
call()runs a function with a chosenthis, as call, apply, and bind shows. Line 6 keeps the root. Line 7 returns it, so the card notices nothing. - Line 12 loads the closed card from earlier in this lesson.
- Line 14 prints
null. The card's root is still closed. - Line 16 prints
closed Green tea. The page has the root anyway. - Line 17 changes the name. The result shows Free tea.
attachShadow() before the card loaded. When the card calls it, the same closed root goes to two places: the card's #root, and the page's kept array.You buy a strong lock for the shop door. The locksmith fits it, and quietly cuts a spare key for himself. The lock works. People walking past can't open the door. The locksmith can.
- In real life: The strong lock
- In JavaScript:
mode: "closed" - In real life: The locksmith, who fits every lock
- In JavaScript:
Element.prototype.attachShadow, which every component calls - In real life: Cutting a spare key first
- In JavaScript: A wrapper that keeps each root in
kept - In real life: People walking past
- In JavaScript: Scripts that only try
card.shadowRoot
web.dev's guide to shadow DOM makes the same point. Nothing stops a script from taking over attachShadow. Any script that runs before the component can do it.
Asking for the card's internals first
Internals can leak the root too. attachInternals() doesn't check who calls it. If the card never asked for its internals, the page can:
<tea-card price="4"></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const internals = card.attachInternals(); console.log(internals.shadowRoot.mode); console.log(internals.shadowRoot.querySelector("p").textContent);</script>Line 6 asks for the closed card's internals, from the page. Line 7 prints closed, and line 8 prints Green tea. The page read the root through them.
The fix is to ask first. Each element hands out its internals once. A second call throws a NotSupportedError. So a closed component should call this.attachInternals() in its constructor, even before it needs them. Exercise 6 makes that change. A component that never uses internals can also turn them off. static disabledFeatures = ["internals"] makes every call throw. Safari doesn't support that option.
Extensions and DevTools
Tools with more power than a page see closed roots too:
- DevTools shows them, as you saw. You can change them there.
- Chrome extensions can call chrome.dom.openOrClosedShadowRoot(). It returns a closed root as easily as an open one.
- In WebKit, Safari's engine, some script worlds get closed roots from
shadowRoot. Its source checks a flag for that.
So never put anything in a component that other code on the page must not read. Keep secrets on the server. Now sort these ways of reaching a closed card's root:
card.shadowRoot, from the pagedocument.querySelector("tea-card p")event.composedPath()in a page listener- Playwright's
page.locator("tea-card p") this.#root, inside the classbutton.getRootNode(), in a listener inside the rootthis.attachInternals().shadowRoot, in the constructor- A wrapper on
Element.prototype.attachShadow, loaded first card.attachInternals().shadowRoot, from the page
The card's shadow root is closed. Sort each piece of code by what it gets.
Should you use open or closed shadow DOM?
Use open, unless you have a clear reason not to. The people who build the platform and its tools say the same:
- web.dev, from Google, files closed roots under "should avoid". It calls them "not a security feature". It adds that page authors can't fix styles you forgot to expose.
- Lit, a popular library for web components, makes an open root by default. Its components find their own nodes through
this.renderRoot, the root thatattachShadow()returned. - Playwright, a testing tool, finds elements inside open roots. Its docs say closed roots "are not supported".
What closed costs
Tests lose the most. A test often checks what a component shows inside. With a closed card, Playwright's page.locator("tea-card p") finds 0 paragraphs. Even getByRole("button") finds no button inside. Your tests have to work through the public API only. Page authors lose something too. If your card has a bug, they can't patch around it.
When closed makes sense
Closed mode copies the browser's own elements. In lesson 6.1, a video's controls sat in a root no page could reach. The browser can rebuild them without breaking pages, like the kettle with a sealed base. Closed mode puts the same sign on your component: these insides may change, so build on the public API.
That sign helps most when all three of these are true:
- Your component runs on pages you don't control, like a widget other sites embed.
- Its public API is complete: attributes, properties, events, parts, and custom properties.
- You test it through that public API.
Even then, closed mode only keeps out accidents. It never replaces keeping secrets off the page.
Testing the kit's tea card
The kit's tea-card from lesson 6.1 keeps its open root. Here's why. This page checks the card the way a test would. It loads the kit, then reads what the card shows:
<tea-card name="Green tea" price="4"></tea-card> <script type="module"> import "./tea-kit/index.js"; const card = document.querySelector("tea-card"); const name = card.shadowRoot.querySelector("h3").textContent; const price = card.shadowRoot.querySelector("p").textContent; console.log(name === "Green tea" ? "PASS: the name" : "FAIL: the name"); console.log(price === "Price: 4" ? "PASS: the price" : "FAIL: the price");</script>- Line 1 is a card for Green tea at 4.
- Line 4 loads the whole kit.
- Lines 7 and 8 read the heading and the price line, through
card.shadowRoot. - Lines 9 and 10 print
PASS: the nameandPASS: the price.
With a closed card, line 7 would throw a TypeError, because shadowRoot would be null. The check would need a way around the closed root. An open root keeps checks like this short.
Open doesn't make the insides part of the API. The kit's public API is the name and price attributes. Its insides may change. Open mode only lets tests and page authors look.
Common mix-ups
- "Closed mode keeps my component's secrets safe." No. A script that runs first can wrap
attachShadow(). The page can ask for the internals if the component didn't. Extensions and DevTools see closed roots too. - "With a closed root, even my own class can't reach it." No.
attachShadow()returns it,getRootNode()climbs to it, andattachInternals().shadowRootgives it. - "Closed mode hides the content from styles and screen readers." No. A closed root is drawn, styled with
::part()and inherited styles, and read by screen readers, like an open one. - "attachInternals().shadowRoot only works for closed roots." No. It gives open roots too. It gives
nullfor a root that isn't the class's own, like one the page attached before the upgrade. - "If I leave out mode, I get an open root." No.
modeis required. Leaving it out throws aTypeError. - "Closed mode stops events from reaching the page." No. Events cross out the same way, with the host as their target. Only the page's
composedPath()leaves out the nodes inside.
Practice exercises
Answer first, then use the hints. Each one runs, so you can check yourself.
What do lines 3 and 4 print?
const div = document.createElement("div");
const root = div.attachShadow({ mode: "closed" });
console.log(div.shadowRoot === root);
console.log(root.host === div);false, then true. The div's shadowRoot is null, so it isn't root. But a closed root still knows its host.
The card dispatches an event from a paragraph inside its closed root. What does line 3 print?
<script> document.addEventListener("tea-ready", (event) => { console.log(event.composedPath()[0].localName); });</script> <tea-card></tea-card> <script> class TeaCard extends HTMLElement { #root = this.attachShadow({ mode: "closed" }); connectedCallback() { this.#root.innerHTML = "<p>Green tea</p>"; const ready = new Event("tea-ready", { bubbles: true, composed: true }); this.#root.querySelector("p").dispatchEvent(ready); } } customElements.define("tea-card", TeaCard);</script>tea-card. The event is composed, so it reaches the page. But the paragraph is in a closed root, so the page's path starts at the host.
The card stays empty, and the console shows an error. Which error, and how do you fix it?
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "closed" }); this.shadowRoot.innerHTML = "<p>Green tea</p>"; } } customElements.define("tea-card", TeaCard);</script><tea-card></tea-card> <script> class TeaCard extends HTMLElement { #root; constructor() { super(); this.#root = this.attachShadow({ mode: "closed" }); this.#root.innerHTML = "<p>Green tea</p>"; } } customElements.define("tea-card", TeaCard);</script>A TypeError: Cannot set properties of null (setting 'innerHTML'). With a closed root, this.shadowRoot is null for the class too. Keeping the return value in #root fixes it.
Follow the two comments. What does your constructor print?
<tea-card> <template shadowrootmode="closed"> <p>Price: 4</p> </template></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); // 1. Get the card's shadow root through its internals. // 2. Print the text of the paragraph inside it. } } customElements.define("tea-card", TeaCard);</script><tea-card> <template shadowrootmode="closed"> <p>Price: 4</p> </template></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachInternals().shadowRoot; console.log(root.querySelector("p").textContent); } } customElements.define("tea-card", TeaCard);</script>It prints Price: 4. The browser built the closed root from the HTML, and the internals hand it to the class.
Write the wrapper from memory, then print the closed card's price. What does your last line print?
<script> const kept = []; // Wrap Element.prototype.attachShadow so it pushes // every root it makes into kept.</script> <tea-card price="4"></tea-card><script src="tea-card.js"></script><script> // Print the card's price, from the second paragraph in kept[0].</script><script> const kept = []; const attach = Element.prototype.attachShadow; Element.prototype.attachShadow = function (options) { const root = attach.call(this, options); kept.push(root); return root; };</script> <tea-card price="4"></tea-card><script src="tea-card.js"></script><script> console.log(kept[0].querySelector("p + p").textContent);</script>It prints Price: 4. The wrapper ran before the card loaded, so it kept the card's closed root.
Change tea-card.js so the page can't get the card's internals. What does the page print then?
<tea-card price="4"></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); try { card.attachInternals(); console.log("The page got the internals"); } catch (error) { console.log(error.name); }</script><tea-card price="4"></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); try { card.attachInternals(); console.log("The page got the internals"); } catch (error) { console.log(error.name); }</script>It prints NotSupportedError. The card took its internals while it was being built. Each element hands out its internals once, so the page's call throws.
Check your understanding
For each question, ask who is looking: code inside the root, or code outside it.
Question 1 of 7What does
card.shadowRootgive for a card whose shadow root is closed?Choose an answer to see the explanation.
Question 2 of 7What does
this.attachShadow({ mode: "closed" })return?Choose an answer to see the explanation.
Question 3 of 7In the closed version of the playground, what does line 20 print after a click on Green tea?
Read the code, then predict<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); const root = this.attachShadow({ mode: "closed" }); root.innerHTML = "<p>Click me: Green tea</p>"; root.addEventListener("click", (event) => { console.log("Inside, the path starts at", event.composedPath()[0].localName); }); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); console.log("card.shadowRoot is", card.shadowRoot ? "a ShadowRoot" : "null"); document.addEventListener("click", (event) => { console.log("The page sees the target", event.target.localName); console.log("The page's path starts at", event.composedPath()[0].localName); }); </script>Choose an answer to see the explanation.
Question 4 of 7A constructor attaches an open shadow root. What does
this.attachInternals().shadowRootgive?Choose an answer to see the explanation.
Question 5 of 7The page attaches a closed shadow root to
<tea-card>before the class is defined. What does the class'sinternals.shadowRootgive?Choose an answer to see the explanation.
Question 6 of 7Why isn't a closed shadow root a security feature?
Choose an answer to see the explanation.
Question 7 of 7Which of these still reaches inside a closed tea card?
Choose an answer to see the explanation.
Key takeaways
modedecides one thing: whetherelement.shadowRootgives the root (open) ornull(closed). You must always pass it.attachShadow()returns the root in both modes. Keep it in a private field like#root.- Outside a closed root,
composedPath()starts at the host, andassignedSlotisnull. Inside, nothing changes. - Drawing, styles, events, focus, screen readers, find in page, and DevTools work the same in both modes.
shadowRootis alsonullbefore the upgrade, on built-in elements, and when there's no root.this.attachInternals().shadowRootgives a class its own root, open or closed, even one built from HTML.- Closed isn't security. A wrapper on
attachShadow(), an earlyattachInternals(), extensions, and DevTools all get in. Use open unless you have a clear reason.
Remember the one-liner.
Closed mode makes shadowRoot give null. It stops accidents, not code that's trying.
Sources
The facts on this page come from these standards, docs, and source files:
- Element: attachShadow(), open and closed shadow roots, MDN.
- ShadowRoot: mode, MDN.
- DOM Standard: the shadowRoot getter, WHATWG.
- Private elements, MDN.
- DOM Standard: closed-shadow-hidden, WHATWG.
- Event: composedPath(), MDN.
- Using shadow DOM: Element.shadowRoot and the mode option, MDN.
- DOMModel.ts, how DevTools names a shadow root, Chrome DevTools source, chromium/8127 branch.
- Element: shadowRoot, MDN.
- ElementInternals: shadowRoot, MDN.
- HTML Standard: shadow root access, WHATWG.
- DOM Standard: attach a shadow root, WHATWG.
- Declarative shadow DOM, Mason Freed and Jason Miller, web.dev.
- Shadow DOM v1: Self-contained web components, creating closed shadow roots, Eric Bidelman, web.dev.
- HTMLElement: attachInternals(), MDN.
- chrome.dom: openOrClosedShadowRoot(), Chrome for Developers.
- element.cc, OpenShadowRoot() and ClosedShadowRoot(), Chromium source at 158.0.8127.18.
- Element.cpp, shadowRootForBindings(), WebKit source at WebKit-7625.2.8.
- Locators: locate in Shadow DOM, Playwright docs.
- Working with Shadow DOM: customizing the render root, Lit docs.
Coming next: What encapsulation means, the next lesson in this stage. It shows what stays inside a shadow root, like queries, ids, and styles, and what still crosses.