What is shadow DOM?
What is shadow DOM? It's a private DOM tree inside one element. Learn how attachShadow works, what it hides from the page, and which elements can host one.
- 01Give an element a shadow rootCall
attachShadow()once, in the constructor, and fill the shadow root it gives back. - 02Move between the host and its rootUse
shadowRoot,host, andgetRootNode(), and say what the page can and can't reach inside. - 03Know which elements can have oneTell which tags can host a shadow root, and why
<input>and<video>keep the browser's own.
What is shadow DOM?
Leaf and Kettle has a blog. Asha wrote a small script for it. The script finds every <h3> in a post and lists them at the top, as the contents. The blog's CSS also makes every <h3> pink and uppercase.
Then Ravi puts his tea card in a post. The card has an <h3> of its own, for the tea's name. Now Green tea shows up in Asha's contents, as if it were a chapter. And it turns pink and shouts in capitals. Nobody made a mistake. The page and the card share one tree, so each can reach the other's parts. Can a component keep its insides to itself?
Shadow DOM is a private DOM tree that belongs to one element. The browser draws it on the page, but the page's queries and CSS rules don't reach inside it. You add one with attachShadow(). In Chrome, nearly one page load in four calls it.
The DOM is the tree of objects the browser builds from your HTML, as the DOM tree lesson shows. Here is the smallest shadow DOM there is:
<h3>Our story</h3><div id="card"></div> <script> const card = document.querySelector("#card"); const shadow = card.attachShadow({ mode: "open" }); shadow.innerHTML = "<h3>Green tea</h3>"; const headings = document.querySelectorAll("h3"); console.log(headings.length);</script>- Line 1 is a normal heading on the page, Our story.
- Line 2 is an empty
<div>. It's about to get a shadow root. - Line 5 finds the div.
- Line 6 calls
attachShadow(). It gives the div a new, empty tree and returns the top node of that tree, the shadow root.mode: "open"lets other code reach the root later, throughcard.shadowRoot. The next lesson covers the other mode. - Line 7 puts a heading, Green tea, inside the shadow root. A shadow root has
innerHTML, like an element. - Line 9 asks the page for every
<h3>. Line 10 prints how many it found:1.
The result shows both headings. But the page's query found only one. Green tea is drawn on the page, yet it isn't part of the page's tree. That's what Asha's script needs. It would list Our story and skip the card.
<body>, the heading Our story, and the <div>. The div is the shadow host. Its shadow root starts a second tree, the shadow tree, with the other heading. The page's query stops at the edge of that tree, the shadow boundary, so it finds 1 heading.Four words name the pieces. You'll meet them in every article about shadow DOM:
- Shadow host: the element that has a shadow root. Here, it's the
<div>. - Shadow root: the top node of the private tree.
- Shadow tree: the shadow root and everything inside it.
- Shadow boundary: the edge between the shadow tree and the page. The page's queries and selectors stop there.
Leaf and Kettle keeps its cakes in a glass cabinet by the till. Every customer can see them. Nobody can reach in and move one by accident. The staff open the cabinet from the back, where the door is.
- In real life: The glass cabinet
- In JavaScript: The shadow host, the
<div> - In real life: The cakes on its shelves
- In JavaScript: The shadow tree
- In real life: The glass front
- In JavaScript: The shadow boundary
- In real life: Customers can see the cakes, but can't touch them
- In JavaScript: The page draws the shadow tree, but its queries and CSS don't reach in
- In real life: Staff open the cabinet from the back
- In JavaScript: The component's own code uses
this.shadowRoot
Shadow DOM gives one element a private tree of its own. You make it with attachShadow(). The browser draws that tree in place of the element's children. The page's queries and CSS rules stop at its edge, the shadow boundary.
Lesson 1.1 gave you a first look: a page's p rule couldn't color a paragraph inside a shadow root. This lesson opens stage 3 and builds shadow roots properly, from the component author's side.
How does attachShadow() work?
In a component, the class attaches the shadow root to itself. Inside the class, this is the element. So this.attachShadow() makes the element the host:
<tea-card></tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: "open" }); shadow.innerHTML = "<p>Green tea</p>"; console.log(shadow.constructor.name); console.log(shadow === this.shadowRoot); } } customElements.define("tea-card", TeaCard);</script>- Line 1 puts a tea card on the page.
- Line 5 is the constructor. It runs once, when the browser makes the card. Line 6,
super(), letsHTMLElementset the element up first. - Line 7 attaches an open shadow root. It keeps what
attachShadow()gives back inshadow. - Line 8 fills the shadow root with a paragraph.
- Line 9 prints what kind of object it is:
ShadowRoot. - Line 10 prints
true. WhatattachShadow()gave back andthis.shadowRootare the same shadow root.
So you can keep the return value, or read this.shadowRoot when you need the root. Both lead to the same place.
One shadow root per element
An element gets one shadow root, for good. A second call throws an error:
const card = document.createElement("div");
card.attachShadow({ mode: "open" });
card.attachShadow({ mode: "open" });Line 1 makes a div. Line 2 gives it a shadow root. Line 3 tries again and throws a NotSupportedError. In Chrome, the message reads Shadow root cannot be created on a host which already hosts a shadow tree. Asking for a different mode doesn't help. The second call throws either way.
There's one exception: a shadow root written in the HTML itself. You'll meet those in Server rendering.
Where to call attachShadow()
So where should the call go? The constructor runs once for each card. connectedCallback() runs each time the card joins a page, as lesson 3.3 showed, and a move counts. Pick one, then press Move the card in the result:
<tea-card></tea-card><div id="shelf">On the shelf:</div><button>Move the card</button> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = "<p>Green tea</p>"; } connectedCallback() { console.log("connectedCallback runs"); } } customElements.define("tea-card", TeaCard); document.querySelector("button").addEventListener("click", () => { document.querySelector("#shelf").append(document.querySelector("tea-card")); });</script>The move runs connectedCallback() again, so the console says it twice. But attachShadow() sits in the constructor, which ran once, when the card was made. Nothing throws, and the card moves to the shelf with Green tea inside.
With the constructor, the move is harmless. With connectedCallback(), the move runs attachShadow() again, and the console shows a NotSupportedError. That's why the shadow root belongs in the constructor. Lesson 3.2 showed that this is allowed: a shadow root isn't a child, so the constructor may attach one and fill it.
What happens to the host's own children?
A host can still have children: the text and elements written inside its tag. They are its light DOM, the normal tree that lesson 5.5 worked with. What does the browser draw when a host has both?
<tea-card>Black tea</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = "<p>Today's tea</p>"; } } customElements.define("tea-card", TeaCard); console.log(document.querySelector("tea-card").textContent);</script>- Line 1 writes Black tea inside the card. That text is the card's light DOM.
- Lines 7 and 8 give the card a shadow root with Today's tea in it.
- Line 13 prints the card's
textContent:Black tea.
The result shows only Today's tea. Black tea is still inside the card, as line 13 proves. It just isn't drawn. Once an element has a shadow root, the browser draws the shadow tree instead of its children.
A shop pastes a big poster over its window. The goods are still on the shelf behind the glass. People walking past only see the poster. Cut a hole in it, and they can see the goods through it again.
- In real life: The goods on the shelf behind the glass
- In JavaScript: The host's children, its light DOM
- In real life: The poster pasted over the window
- In JavaScript: The shadow tree, drawn instead
- In real life: A hole cut in the poster
- In JavaScript: A
<slot>, which shows the children again
That hole is a <slot>. Lesson 1.1 gave you a first taste of one. The lessons on slots in this stage show how to put each child exactly where you want it.
What is the difference between a shadow root and a shadow host?
The host is an element on the page, like the <tea-card>. The shadow root is a separate node that hangs from it. Each one knows the other.
From here on, the card's class lives in its own file, tea-card.js. Click the second tab to see it. It's the card from above, with Green tea in its shadow root.
<tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const shadow = card.shadowRoot; console.log(shadow.host === card); console.log(shadow instanceof DocumentFragment); console.log(shadow.nodeName);</script>- Line 3 loads the card's class.
- Line 6 reads the card's
shadowRoot. That's the way from the host to its root. - Line 7 checks the way back. The root's
hostis the card, so it printstrue. - Line 8 prints
truetoo. A shadow root is a kind ofDocumentFragment: a node that holds other nodes but isn't an element. A<template>keeps its content in the same kind of node. - Line 9 prints its node name,
#document-fragment.
Since a shadow root isn't an element, it has no tag and no attributes. It's only the top of a tree. The host is the element the page can see and style.
At a hotel, you leave your suitcase at the desk. The suitcase gets a tag with your name on it. You get a claim ticket. Each one leads to the other: the ticket finds the suitcase, and the tag finds you.
- In real life: You, the guest
- In JavaScript: The host,
<tea-card> - In real life: Your suitcase
- In JavaScript: The shadow root
- In real life: The claim ticket in your pocket
- In JavaScript:
card.shadowRoot, which leads to the root - In real life: The tag on the suitcase, with your name
- In JavaScript:
shadow.host, which leads back to the card
Walking up from inside
Now start from the paragraph inside the shadow tree, and walk up:
<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.parentNode === card.shadowRoot); console.log(name.parentElement); console.log(name.getRootNode() === card.shadowRoot); console.log(name.getRootNode({ composed: true }) === document); console.log(name.isConnected);</script>- Line 6 finds the paragraph, searching from the shadow root.
- Line 7 prints
true. The paragraph'sparentNodeis the shadow root. - Line 8 prints
null.parentElementonly gives an element, and a shadow root isn't one. So the walk up stops at the root. It never reaches the card. - Line 9 prints
true.getRootNode()gives the top of the tree a node is in. For this paragraph, that's the shadow root. For a node in the page, it'sdocument. - Line 10 prints
true. With{ composed: true },getRootNode()climbs out through each host, up todocument. - Line 11 prints
true.isConnectedsays whether a node is on the page. The paragraph counts, because its host is on the page.
shadowRoot leads to its shadow root, and the root's host leads back. Inside, the paragraph's parentNode and getRootNode() both give the shadow root.getRootNode() answers the question "which tree am I in?". It's like asking which room you're in. { composed: true } asks which building. Exercise 5 uses it to tell the two trees apart.
Can document.querySelector find elements in shadow DOM?
No. document.querySelector() and querySelectorAll() search the page's tree only. They never step into a shadow root. The first example showed it with headings. Now try six ways to look for the card's paragraph:
<p>Our teas</p><tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); console.log(document.querySelector("tea-card p"));</script>To the page's selectors, the card has no <p> inside it. The paragraph lives in the shadow tree, where page queries don't look.
Four lookups miss, and two find it. The two that find it both start at card.shadowRoot. To search a shadow tree, start from its root. Walking and searching the DOM covers the methods themselves.
The same id, twice
Ids work the same way. An id has to be unique, but only inside its own tree. So the page and a component can both use id="price":
<p id="price">Menu price: 5</p><tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); console.log(document.querySelectorAll("#price").length); console.log(document.getElementById("price").textContent); console.log(card.shadowRoot.getElementById("price").textContent);</script>- Line 1 gives a paragraph on the page the id
price. - In the
tea-card.jstab, line 5 gives the card's paragraph the same id. - Line 7 prints
1. The page has one element with that id. - Line 8 prints
Menu price: 5.document.getElementById()only looks in the page. - Line 9 prints
Card price: 4. A shadow root has its owngetElementById(), and it only looks inside.
This helps a lot when you write components. You can use short ids and class names, like price or name. They can't clash with the ones on the page.
What the host's own HTML holds
The host's innerHTML and textContent only hold its children. In the light DOM example, textContent gave Black tea, not Today's tea. In the playground, the card had 0 children. The shadow tree has its own innerHTML, on the shadow root. Saving a host as HTML leaves its shadow tree out too. Server rendering shows how to keep it.
CSS rules from the page
Page CSS stops at the boundary as well. Lesson 1.1 showed a page's p rule miss a paragraph in a shadow root. Lesson 2.3 showed why page selectors can't reach in, and the two ways a component lets the page style it. The next lessons in this stage go deeper into what this privacy covers.
Which elements can have a shadow root?
Not every element. Lesson 5.7 noted that a <button> can't have one. The DOM Standard keeps an exact list, called the valid shadow host names. It has every custom element name, and these 18 HTML tags:
<div>,<span>,<p>, and<blockquote>;<section>,<article>,<aside>,<nav>, and<main>;<header>,<footer>, and<body>;- the six headings,
<h1>to<h6>.
Any other element throws a NotSupportedError. Pick a tag, and the page tries it in your own browser:
<script> const element = document.createElement("div"); try { element.attachShadow({ mode: "open" }); console.log("It worked"); } catch (error) { console.log(error.name); }</script><div> is on the DOM Standard's list of elements that can host a shadow root.
For a tag that isn't on the list, Chrome's message reads This element does not support attachShadow. A custom element name works even before its tag is defined. So a <tea-card> can host a shadow root before customElements.define() runs. SVG elements throw too, because the list only covers HTML elements.
attachShadow() throw a NotSupportedError.Why the list is short
The DOM Standard gives the reason. The list is short on purpose, so browsers can give their own elements shadow roots later. Many already have one. Chrome builds <input>, <textarea>, <select>, and <video> inside shadow roots of its own. The next section looks inside one.
Do you need a shadow root around a button or an image? Put it inside a host. A <tea-card> can hold a <button> or an <img> in its shadow tree. Now sort these tags:
<article><nav><h4><tea-menu><main><textarea><select><li><form><label>
Sort each tag by what attachShadow() does with it.
Do built-in elements use shadow DOM?
Yes. Browsers built some of their own elements this way before page authors could. In 2011, Dimitri Glazkov wrote about how a range slider hides its track and thumb in a shadow tree. A video hides its buttons the same way. Shadow DOM gave page authors the same tool.
Lesson 1.1 showed that a slider's shadowRoot is null, and how to see its insides in DevTools. Now look at a video player, the one you've clicked for years:
<video controls width="240"></video> <script> const video = document.querySelector("video"); console.log(video.shadowRoot); try { video.attachShadow({ mode: "open" }); } catch (error) { console.log(error.name); }</script>- Line 1 is a video with controls, and no file to play. Chrome still draws its play button and the rest of its bar.
- Line 5 prints
null. The page can't see the video's shadow root. - Line 7 tries to attach a shadow root of the page's own. Line 9 prints
NotSupportedError.
These are user-agent shadow roots. The user agent is the browser, and these roots belong to it. Page scripts can't open them, so shadowRoot is always null. Turn on Show user agent shadow DOM in DevTools, as in lesson 1.1. Then Chrome's Elements panel shows this under the video:
<video controls width="240">
#shadow-root (user-agent)
<div pseudo="-webkit-media-controls">
<div pseudo="-webkit-media-controls-enclosure">
<div pseudo="-webkit-media-controls-panel">
<div pseudo="-internal-media-controls-button-panel">
<input type="button" pseudo="-webkit-media-controls-play-button" aria-label="play">
…Line 2 is the browser's shadow root. Lines 3 to 6 are boxes inside boxes. Line 7 is the play button: an <input type="button"> with the label play. The controls you click every day are plain HTML, like your own components. Lesson 1.4 shows more ways to inspect shadow roots.
You press a kettle's switch every morning. The wiring sits in a sealed base. You can't open it, and you don't need to. The maker can change the wiring, and your kettle still works the same way.
- In real life: The kettle's switch
- In JavaScript: The play button you click
- In real life: The sealed base, with the wiring inside
- In JavaScript: The video's user-agent shadow root
- In real life: The maker, who built the wiring
- In JavaScript: The browser
- In real life: No screws to open the base
- In JavaScript:
video.shadowRootisnull
That last part matters. The browser can change how it builds a video's controls, and no page breaks, because no page can reach them. Your components get the same freedom. You can change their insides without breaking the pages that use them.
Adding a tea card to the tea kit
Back to Asha's blog. Lesson 3.1 said the kit's tea-card would come back with shadow DOM. Here it is: the kit's first component with a shadow root. This page has the blog's pink headings, Asha's contents script, and a card:
<style> h3 { color: deeppink; text-transform: uppercase; }</style> <h3>Our story</h3><tea-card name="Green tea" price="4"></tea-card><p id="contents"></p> <script type="module"> import "./tea-kit/index.js"; const titles = [...document.querySelectorAll("h3")].map((h3) => h3.textContent); document.querySelector("#contents").textContent = `Contents: ${titles.join(", ")}`;</script>- Line 2 makes every
<h3>pink and uppercase. - Line 6 is the card, with a
nameand aprice. - Line 10 loads the whole kit, as in earlier lessons.
- Line 12 collects the text of every
<h3>on the page. Line 13 writes them out as the contents.
The result shows OUR STORY in pink capitals. Then comes the card, with Green tea in green, and then Contents: Our story. The blog's rule didn't change the card's heading. The script didn't list it. Both problems from the start of the lesson are gone.
Here is the card's 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>
<div class="card">
<h3></h3>
<p></p>
</div>`;
}
attributeChangedCallback(name, oldValue, newValue) {
const text = newValue ?? "";
if (name === "name") this.shadowRoot.querySelector("h3").textContent = text;
if (name === "price") this.shadowRoot.querySelector("p").textContent = `Price: ${text}`;
}
}
customElements.define("tea-card", TeaCard);- Lines 1 to 7 describe the card. The kit's
custom-elements.jsonlists the same details, as lesson 5.4 set up. - Line 9 asks the browser to watch the
nameandpriceattributes, as in lesson 3.4. - Line 13 attaches the shadow root in the constructor, once per card.
- Lines 14 to 23 fill it: a
<style>, then a box with an empty heading and an empty paragraph. - Lines 16 to 18 style the box, its heading, and its paragraph. These rules only apply inside this shadow root. The card's
h3rule can't turn Asha's headings green. Herh3rule can't turn the card's heading pink. - Lines 26 to 30 run when an attribute changes, including when it's first set. Line 28 writes the name into the heading. Line 29 writes the price line,
Price: 4.
Lines 28 and 29 set textContent, never innerHTML. So a tea's name can only ever be text. It can never turn into HTML. The card's shadow root also uses short, plain names: .card, h3, and p. Inside a shadow tree, they can't clash with the page.
Common mix-ups
- "Shadow DOM is a kind of virtual DOM." No. A shadow tree is made of real DOM nodes, and the browser draws them. A virtual DOM is a copy of the page that a library like React keeps in JavaScript.
- "You can attach a shadow root to any element." No. Only custom elements and 18 HTML tags can have one. A
<button>, an<input>, or an<img>throws aNotSupportedError. - "Calling attachShadow() twice is harmless." No. The second call throws a
NotSupportedError. Attach the shadow root in the constructor, which runs once. - "Shadow DOM hides content from screen readers and search." No. The shadow tree is drawn. The accessibility tree includes it, and find in page finds its text.
- "Shadow DOM keeps a component's secrets safe." No. Any script on the page can reach an open shadow root through
shadowRoot. It stops accidents, not people. - "You make a shadow root with createShadowRoot()." No. That was an early draft that only Chrome had, and Chrome removed it in Chrome 80, in 2020. Today it's
attachShadow()in every browser.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
The page shows three headings. What does the console print?
<h2>Menu</h2><section id="specials"></section> <script> const specials = document.querySelector("#specials"); specials.attachShadow({ mode: "open" }); specials.shadowRoot.innerHTML = "<h2>Today</h2><h2>Tomorrow</h2>"; console.log(document.querySelectorAll("h2").length);</script>1. The page shows three headings, but only Menu is in the page's tree. Today and Tomorrow live in the section's shadow root.
The loop tries to attach a shadow root to three new elements. Which one throws?
for (const tag of ["p", "button", "tea-card"]) {
try {
document.createElement(tag).attachShadow({ mode: "open" });
console.log(tag, "works");
} catch (error) {
console.log(tag, error.name);
}
}button. It prints p works, then button NotSupportedError, then tea-card works. A button isn't on the list.
Follow the three comments. What does your last line print? And what happens to Black tea on the page?
<section id="specials">Black tea</section> <script> const specials = document.querySelector("#specials"); // 1. Give specials an open shadow root. // 2. Put <p>Today: Oolong</p> inside it. // 3. Print specials.shadowRoot.host.id</script><section id="specials">Black tea</section> <script> const specials = document.querySelector("#specials"); specials.attachShadow({ mode: "open" }); specials.shadowRoot.innerHTML = "<p>Today: Oolong</p>"; console.log(specials.shadowRoot.host.id);</script>It prints specials. The page now shows Today: Oolong, and Black tea is no longer drawn: the shadow tree is drawn instead of the section's children.
The console shows an error when this page loads. Which error, and how do you fix it?
<tea-card></tea-card><div id="shelf"></div> <script> class TeaCard extends HTMLElement { connectedCallback() { this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = "<p>Green tea</p>"; } } customElements.define("tea-card", TeaCard); document.querySelector("#shelf").append(document.querySelector("tea-card"));</script><tea-card></tea-card><div id="shelf"></div> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = "<p>Green tea</p>"; } } customElements.define("tea-card", TeaCard); document.querySelector("#shelf").append(document.querySelector("tea-card"));</script>A NotSupportedError. The move runs connectedCallback() a second time, so attachShadow() runs twice. In the constructor, it runs once.
Write whereIs(). Use getRootNode(). What does the second console.log() print?
<p>Our teas</p><tea-card></tea-card> <script src="tea-card.js"></script><script> function whereIs(node) { // Return "the page" when node is in the page, // or "inside tea-card" when it's in tea-card's shadow root. } const card = document.querySelector("tea-card"); console.log(whereIs(document.querySelector("p"))); console.log(whereIs(card.shadowRoot.querySelector("p")));</script><p>Our teas</p><tea-card></tea-card> <script src="tea-card.js"></script><script> function whereIs(node) { const root = node.getRootNode(); if (root === document) return "the page"; return `inside ${root.host.localName}`; } const card = document.querySelector("tea-card"); console.log(whereIs(document.querySelector("p"))); console.log(whereIs(card.shadowRoot.querySelector("p")));</script>The first line prints the page, and the second prints inside tea-card. getRootNode() gives the shadow root, and its host is the card.
In Chrome, inspect this video with user-agent shadow DOM turned on. Which HTML element is its play button?
<video controls width="240"></video>An <input>, with type="button". Chrome builds the play button from a plain input, deep inside the video's user-agent shadow root.
Check your understanding
For each question, picture the two trees: the page's tree, and the private one that hangs from the host.
Question 1 of 7What does
attachShadow()give back?Choose an answer to see the explanation.
Question 2 of 7What does the headings example print?
Read the code, then predict<h3>Our story</h3> <div id="card"></div> <script> const card = document.querySelector("#card"); const shadow = card.attachShadow({ mode: "open" }); shadow.innerHTML = "<h3>Green tea</h3>"; const headings = document.querySelectorAll("h3"); console.log(headings.length); </script>Choose an answer to see the explanation.
Question 3 of 7Which of these elements can have a shadow root?
Choose an answer to see the explanation.
Question 4 of 7A card calls
attachShadow()inconnectedCallback(). What happens when the page moves the card?Choose an answer to see the explanation.
Question 5 of 7What does
name.getRootNode()give back for a paragraph inside a tea card's shadow root?Choose an answer to see the explanation.
Question 6 of 7Does a screen reader read the text inside a shadow root?
Choose an answer to see the explanation.
Question 7 of 7Why does
document.querySelector("input").shadowRootgivenull?Choose an answer to see the explanation.
Key takeaways
- Shadow DOM is a private DOM tree attached to one element, the host. Its top node is the shadow root.
attachShadow()gives back the shadow root. Call it once, in the constructor. A second call throws aNotSupportedError.- Once an element has a shadow root, the browser draws the shadow tree instead of its children. Slots show them again.
element.shadowRootleads to the root, andshadowRoot.hostleads back.getRootNode()says which tree a node is in.- Page queries, ids, and CSS selectors stop at the shadow boundary. Inherited styles, events, find in page, and screen readers still cross it.
- It isn't a security boundary. Any script can reach an open shadow root.
- Only custom elements and 18 HTML tags can host a shadow root.
<input>,<video>, and other built-in elements keep shadow roots of the browser's own.
Remember the one-liner.
Shadow DOM is a private tree for one element: drawn on the page, but out of reach of the page's queries and styles.
Sources
The facts on this page come from these standards, docs, and source files:
- Using shadow DOM, MDN.
- DOM Standard: Shadow tree, WHATWG.
- Element: attachShadow(), MDN.
- DOM Standard: attachShadow() and attach a shadow root, WHATWG.
- Shadow DOM v1: Self-contained web components, Eric Bidelman, web.dev.
- ShadowRoot, MDN.
- ShadowRoot: host, MDN.
- DOM Standard: Interface ShadowRoot, WHATWG.
- Node: getRootNode(), MDN.
- Accessibility features reference: the Accessibility tab, Chrome for Developers.
- find_buffer.cc, Chrome's find in page, Chromium source at 158.0.8127.18.
- DOM Standard: valid shadow host name, WHATWG.
- Element: shadowRoot, MDN.
- What the Heck is Shadow DOM?, Dimitri Glazkov.
- Preferences: Show user agent shadow DOM, Chrome for Developers.
- ElementAttachShadow usage, Chrome Platform Status.
- Web Components update: more time to upgrade to v1 APIs, Chrome for Developers.
Coming next: Open and closed shadow roots, the next lesson in this stage. What mode: "closed" changes, and why it still isn't a lock.