completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Give an element a shadow rootCall attachShadow() once, in the constructor, and fill the shadow root it gives back.
  • 02
    Move between the host and its rootUse shadowRoot, host, and getRootNode(), and say what the page can and can't reach inside.
  • 03
    Know 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:

A div with a heading in its shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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, through card.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.

Two trees from the first example. A window called page holds body, with two children: h3 Our story, and div id card, marked shadow host. An arrow leads from the div to a second window called shadow root, which holds h3 Green tea. On the left, querySelectorAll h3 finds 1 heading.page<body><h3> Our story<div id="card">shadow hostshadow root<h3> Green teaquerySelectorAll("h3")finds 1 heading
The page's tree holds <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.
Real-life analogyThe cake cabinet by the till

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
The main idea

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:

A tea card attaches its own shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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(), lets HTMLElement set the element up first.
  • Line 7 attaches an open shadow root. It keeps what attachShadow() gives back in shadow.
  • Line 8 fills the shadow root with a paragraph.
  • Line 9 prints what kind of object it is: ShadowRoot.
  • Line 10 prints true. What attachShadow() gave back and this.shadowRoot are 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:

Attaching twice (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
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:

Playground: where to attach the shadow root
A tea card that the page movesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Press Move the card: the card moves, and nothing throws

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.

Both choices are the same page. Only the place of the two attachShadow() lines changes: lines 9 and 10 in the constructor, or lines 12 and 13 in connectedCallback(). Each run starts a fresh page, so press Move the card in the result to see what a move does.

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?

A card with children and a shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Real-life analogyA poster on the shop window

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.

The host and its root point at each otherPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 host is the card, so it prints true.
  • Line 8 prints true too. A shadow root is a kind of DocumentFragment: 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.

Real-life analogyA suitcase at the hotel desk

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:

Where a paragraph in the shadow tree leadsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 6 finds the paragraph, searching from the shadow root.
  • Line 7 prints true. The paragraph's parentNode is the shadow root.
  • Line 8 prints null. parentElement only 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's document.
  • Line 10 prints true. With { composed: true }, getRootNode() climbs out through each host, up to document.
  • Line 11 prints true. isConnected says whether a node is on the page. The paragraph counts, because its host is on the page.
The tea card and its shadow root. An arrow marked .shadowRoot goes from the tea-card card to a window called shadow root. An arrow marked .host comes back. Inside the window, an arrow rises from the paragraph Green tea to the top of the shadow root, marked parentNode and getRootNode().<tea-card>shadow host.shadowRoot.hostshadow root<p> Green teaparentNodegetRootNode()
The card's 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:

Playground: who can find the card's paragraph?
Look for the card's paragraphPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Line 7 prints null

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.

The page has one paragraph of its own, Our teas, and a tea card whose shadow root holds a paragraph with Green tea (the tea-card.js tab). Each choice changes only line 7.

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":

One id in the page, the same id in the cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 gives a paragraph on the page the id price.
  • In the tea-card.js tab, 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 own getElementById(), 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.

What does shadow DOM not hide?

Shadow DOM hides nodes from the page's code. It doesn't hide them from people. And a few things cross the boundary on purpose:

  • It's drawn. Everything in a shadow tree shows on the page, as in every result in this lesson.
  • Inherited styles pass in. Text color, fonts, and custom properties like --tea-accent reach the shadow tree from the host. Lesson 2.3 themes components this way.
  • Events cross out. A click on a paragraph inside the card reaches the page. Outside, the click seems to come from the card itself. That's called retargeting. Lesson 5.3 showed it, and the lesson on event retargeting covers it in full.
  • Find in page finds it. Press Ctrl+F (Cmd+F on a Mac), and Chrome searches shadow trees too. Its search code walks the drawn tree, shadow roots included.
  • Screen readers read it. The accessibility tree includes shadow trees.

The accessibility tree is the version of the page that screen readers use. It lists each heading, button, and piece of text, with its role and its name. Here is Chrome's accessibility tree for the first example, without the rows for plain text:

Chrome's accessibility tree for the first example (shortened)Text
RootWebArea
  heading "Our story"
  generic
    heading "Green tea"

Line 2 is the page's heading, Our story. Line 3 is the div. Line 4 is the heading from the div's shadow root, Green tea, right under its host. A screen reader reads it like any other heading. To see this yourself, open DevTools and select an element in the Elements panel. Then open the Accessibility tab and turn on Show accessibility tree. Accessible components is all about this tree.

Read each row of this table across: what the page tries, whether it reaches the shadow tree, and why.

What stops at the shadow boundary, and what crosses it
What the page triesDoes it reach the shadow tree?Why
document.querySelector() and querySelectorAll()No.They only search the page's own tree. Start from card.shadowRoot to search inside.
document.getElementById()No.Each tree keeps its own ids, so the same id can be used in both.
A page CSS rule, like p { color: red; }No.Page selectors can't pick elements inside a shadow root.
The host's innerHTML and textContentNo.They hold the host's children. The shadow tree isn't one of them.
Inherited styles, like color and font-familyYes.The shadow tree takes them from the host, the way any child would.
Custom properties, like --tea-accentYes.They're inherited too, so the component can read them with var().
A click inside the componentYes.The click reaches the page, and the page sees the host as its target.
Screen readers and find in pageYes.They work with what the page draws, and the shadow tree is drawn.
A script that reads element.shadowRootYes.An open shadow root is one property away. Shadow DOM is not a lock.

Is shadow DOM a security boundary?

No. Shadow DOM keeps out accidents, like Asha's script picking up Ravi's heading. It doesn't keep out code that's trying. Any script on the page can open an open shadow root and change it:

Any script can change an open shadow rootPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  card.shadowRoot.querySelector("p").textContent = "Free tea";</script>
ResultLoading…

Line 6 reaches into the card through shadowRoot and rewrites its text. The result shows Free tea. Every script on a page runs with the same power. So never put anything in a component that other scripts on the page must not see.

Real-life analogyA Staff only sign

A tea shop's kitchen door says Staff only. Customers don't wander in by mistake, and that's the point. But the sign isn't a lock. Anyone who decides to push the door can walk through.

In real life: The sign on the kitchen door
In JavaScript: The shadow boundary
In real life: Customers who'd never wander in by mistake
In JavaScript: The page's queries and CSS rules
In real life: Someone who pushes the door anyway
In JavaScript: A script that uses element.shadowRoot

The next lesson's closed shadow roots hide the shadowRoot property. They aren't a lock either. MDN says not to treat them as a strong security feature.

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:

Playground: can this element have a shadow root?
Try to attach a shadow rootPop out in the code editor (opens in a new tab)HTML
<script>  const element = document.createElement("div");  try {    element.attachShadow({ mode: "open" });    console.log("It worked");  } catch (error) {    console.log(error.name);  }</script>
ResultLoading…
Try it yourself
It worked

<div> is on the DOM Standard's list of elements that can host a shadow root.

The page makes a new element with the tag you pick and tries to attach an open shadow root. It runs in your own browser, and the console under the code shows what happened.

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.

Two windows. Can host: <div>, <span>, <p>, <section>, <article>, <h1> to <h6>, <main>, <tea-card>, marked attachShadow() works. Throws: <button>, <input>, <img>, <a>, <video>, <select>, <ul>, <textarea>, marked NotSupportedError.can host<div><span><p><section><article><h1> to <h6><main><tea-card>throws<button><input><img><a><video><select><ul><textarea>attachShadow() worksNotSupportedError
A few plain containers, the headings, and every custom element can host a shadow root. Most other tags, like buttons, inputs, images, and links, make 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:

Can this tag have a shadow root?
  • <article>
  • <nav>
  • <h4>
  • <tea-menu>
  • <main>
  • <textarea>
  • <select>
  • <li>
  • <form>
  • <label>
Try it yourself
0 of 10 correct

Sort each tag by what attachShadow() does with it.

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

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:

A video keeps its shadow root to itselfPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Inside <video controls>, in Chrome's Elements panel (shortened)Text
<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.

Real-life analogyA kettle with a sealed base

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.shadowRoot is null

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:

The tea card on Asha's blogPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 makes every <h3> pink and uppercase.
  • Line 6 is the card, with a name and a price.
  • 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:

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

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
      <style>
        .card { border: 2px solid seagreen; border-radius: 8px; padding: 8px 12px; }
        h3 { margin: 0; color: seagreen; }
        p { margin: 4px 0 0; }
      </style>
      <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.json lists the same details, as lesson 5.4 set up.
  • Line 9 asks the browser to watch the name and price attributes, 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 h3 rule can't turn Asha's headings green. Her h3 rule 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 a NotSupportedError.
  • "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.

Exercise 1 · Warm-upCount the headings

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>
ResultLoading…

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

    Exercise 2 · Warm-upWhich tag throws?

    The loop tries to attach a shadow root to three new elements. Which one throws?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    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);
      }
    }

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

      Exercise 3 · PracticeA section of specials

      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>
      ResultLoading…

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

        Exercise 4 · PracticeFind the bug

        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>
        ResultLoading…

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

          Exercise 5 · ChallengeWhich tree is it in?

          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>
          ResultLoading…

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

            Exercise 6 · ChallengeInside the play button

            In Chrome, inspect this video with user-agent shadow DOM turned on. Which HTML element is its play button?

            <video controls width="240"></video>
            ResultLoading…

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

              Check your understanding

              For each question, picture the two trees: the page's tree, and the private one that hangs from the host.

              The shadow DOM quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does attachShadow() give back?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does the headings example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. Question 3 of 7Which of these elements can have a shadow root?

                Choose an answer to see the explanation.

              4. Question 4 of 7A card calls attachShadow() in connectedCallback(). What happens when the page moves the card?

                Choose an answer to see the explanation.

              5. 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.

              6. Question 6 of 7Does a screen reader read the text inside a shadow root?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why does document.querySelector("input").shadowRoot give null?

                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 a NotSupportedError.
              • Once an element has a shadow root, the browser draws the shadow tree instead of its children. Slots show them again.
              • element.shadowRoot leads to the root, and shadowRoot.host leads 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:

              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.

              CompleteFrontend Clear concepts. Working examples.