completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Walking the composed tree

Learn shadow DOM traversal: getRootNode(), deep queries across nested shadow roots, walking the composed tree, and reading selections with getComposedRanges().

By the end, you can
  • 01
    Find the tree a node lives inRead getRootNode() with and without composed: true, and use it to search the right tree.
  • 02
    Search and climb across shadow rootsWrite findAllDeep() and closestDeep(), say the order they visit nodes in, and say what closed roots hide.
  • 03
    Read a selection that crosses a shadow rootUse getComposedRanges() with the shadowRoots option instead of getRangeAt(0).

How do you find nodes across shadow roots?

It's six o'clock, and Leaf and Kettle is closing. Asha wants the menu page to find every Add button, so it can turn them off. Each of Ravi's tea cards has one. She writes document.querySelectorAll("button"). It finds none. Where did the buttons go?

Every shadow root is a tree of its own, and every search stays in the tree it starts in. To search across, you go from tree to tree yourself: down into each open shadow root through its host, and back up through getRootNode().host. Closed shadow roots stay out of reach. And for text the reader selects across a boundary, getComposedRanges() reports both ends.

You met the first half in lesson 6.1 and lesson 6.3: page searches stop at a shadow root. Here is the menu page, with a card and Today's special. The special is a panel with a whole card inside it. The page asks four trees for buttons, one at a time:

Four trees, searched one at a timePop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card><tea-panel></tea-panel> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script>  const card = document.querySelector("tea-card");  const panel = document.querySelector("tea-panel");  const oolong = panel.shadowRoot.querySelector("tea-card");  console.log("The page:", document.querySelectorAll("button").length);  console.log("Green tea's root:", card.shadowRoot.querySelectorAll("button").length);  console.log("The panel's root:", panel.shadowRoot.querySelectorAll("button").length);  console.log("Oolong's root:", oolong.shadowRoot.querySelectorAll("button").length);</script>
ResultLoading…
  • In the tea-card.js tab, line 5 fills the card's shadow root. A heading shows the page's text through a slot, and an Add button sits under it.
  • In the tea-panel.js tab, line 5 puts a label and a whole tea-card, Oolong, in the panel's shadow root.
  • On the page, line 9 finds the Oolong card inside the panel's root. Lines 10 to 13 count the buttons in four trees.

The console prints The page: 0, Green tea's root: 1, The panel's root: 0, and Oolong's root: 1. Two buttons, in two different shadow roots. And one of them belongs to a card that sits inside the panel's root.

Four windows, one per tree. The page window holds two cards, tea-card and tea-panel, and no buttons. An arrow leads from tea-card to a root window holding a button card, labelled Green tea's root. An arrow leads from tea-panel to a root window holding a tea-card card, labelled the panel's root. From that tea-card, an arrow leads to a third root window holding a button card, labelled Oolong's root.pagetea-cardtea-panelno buttonsrootbuttonGreen tea's rootroottea-cardthe panel's rootrootbuttonOolong's root
Each window is one tree. The page holds only the two hosts. Each host's shadow root hangs off it, and the panel's root holds a whole card with a root of its own. querySelectorAll() searches one window at a time.

Put together, these trees make one big tree: the page's tree, with each shadow root hanging off its host. This course calls it the composed tree. The DOM Standard says "shadow-including" for the same idea. The page's own children of a host stay under the host, where the page wrote them.

Real-life analogyThe food hall map and the stalls' floor plans

Leaf and Kettle's tea stall sits in a food hall. The hall's map shows only the stalls' fronts. Each stall can pin its floor plan at its door. To find every kettle in the hall, you walk past each stall and read its plan. One stall keeps its plan to itself. Its kettles never make your list.

In real life: The food hall's own map
In JavaScript: The page's tree
In real life: A stall's floor plan, pinned at its door
In JavaScript: An open shadow root, reached through host.shadowRoot
In real life: Reading every plan as you pass
In JavaScript: A deep query
In real life: A stall that keeps its plan to itself
In JavaScript: A closed shadow root
The main idea

Every search stays in one tree. To cross, step down through each open host's shadowRoot, and climb out through getRootNode().host. Closed roots stay out.

Why it matters: real pages put components inside components. Tests, debugging tools, and focus traps need to see all of it. This lesson covers four things:

  • getRootNode(), to find which tree a node is in.
  • Deep queries, which search every open tree.
  • Walking the composed tree in order, and climbing out with closestDeep().
  • Selections that cross a shadow root, with getComposedRanges().

What does getRootNode() return?

Every tree has a top, called its root. Lesson 6.1 showed that getRootNode() gives a node's root, and { composed: true } climbs out to the document. Now try it on five kinds of node. Pick one:

Playground: where does getRootNode() lead?
Where a node's root isPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script>  const name = (node) => node.localName ?? node.constructor.name;  const card = document.querySelector("tea-card");  const node = card;  console.log("getRootNode():", name(node.getRootNode()));  console.log("composed: true:", name(node.getRootNode({ composed: true })));</script>
ResultLoading…
Try it yourself
A node on the page

The card is the page's own element, so its root is the document. composed: true has no shadow root to climb out of, so it gives the document too.

Only line 7 changes. The console prints the root of that node, then the root with composed: true.
  • Line 5 names a node: its tag name, or its class name when it has no tag. ?? means "if the left side is missing, use the right side". Lesson 9.1 used the same trick.
  • Line 7 is the node the playground changes.
  • Line 8 prints its root. Line 9 prints its root with { composed: true }.

The card prints HTMLDocument twice. Its Add button prints ShadowRoot, then HTMLDocument. The shadow root itself prints ShadowRoot, then HTMLDocument.

The last two nodes aren't on the page. A new card's Add button prints ShadowRoot, then tea-card. A p inside a new div prints div twice.

The DOM Standard explains all five with two rules:

  1. A node with no parent is its own root. Any other node has its parent's root.
  2. With { composed: true }, a root that's a shadow root doesn't count. The climb goes on from its host. The standard calls the end the shadow-including root.

So getRootNode() doesn't always give the document. Inside a component, it gives the shadow root. And a node that isn't on the page gives the top of its own little tree. MDN lists the same three cases.

Climbing from the card's Add button. Left, a window called shadow root: a button card, an arrow, and a ShadowRoot card, labelled getRootNode(), stops here. An arrow marked .host leads out to a window called page: a tea-card card, an arrow, and an HTMLDocument card, labelled composed: true, climbs out to here.shadow rootbuttonShadowRoot.hostpagetea-cardHTMLDocumentgetRootNode()stops herecomposed: trueclimbs out to here
From the Add button, getRootNode() stops at the top of the button's own tree, the card's shadow root. With { composed: true }, it goes on through the host, tea-card, to the document.
Real-life analogyEach stall keeps its own staff list

Every stall in the food hall keeps its own staff list. When Ravi needs Mina, he checks his stall's list, not the hall's. Another stall may have a Mina too. That's fine: each list only names its own staff.

In real life: Ravi, at work in the tea stall
In JavaScript: A node inside a shadow root
In real life: His stall's staff list
In JavaScript: node.getRootNode(), the shadow root
In real life: Looking up Mina on that list
In JavaScript: getElementById() on that root
In real life: The food hall's own list
In JavaScript: The document, from getRootNode({ composed: true })

Finding things in your own tree

Ravi writes a small hint element. Its for attribute names the id of a tip, like a label's for. He uses one hint on the page, and one inside a brewing guide's shadow root. Both tips have the id tip:

A hint that looks up its id in its own treePop out in the code editor (opens in a new tab)HTML
<p id="tip">Steep green tea for 2 minutes.</p><tea-hint for="tip"></tea-hint><tea-guide></tea-guide> <script src="tea-hint.js"></script><script src="tea-guide.js"></script>
ResultLoading…
  • In the tea-hint.js tab, line 3 asks for the hint's root. Line 4 looks up the id there. Line 5 prints the root's class name and the tip.
  • In the tea-guide.js tab, line 5 puts a tip and a hint in the guide's shadow root.
  • On the page, lines 1 and 2 are the page's own tip and hint. Line 3 is the guide.

The console prints HTMLDocument: Steep green tea for 2 minutes., then ShadowRoot: Steep oolong for 4 minutes. Each hint found the tip in its own tree. With document.getElementById() on line 4, both hints would print the green tea tip.

This works because a shadow root and the document share many members:

So code that starts with this.getRootNode() works the same on the page or inside a component. One more use: getRootNode({ composed: true }) === document asks whether a node is on the page. The DOM Standard defines isConnected that way, so use that instead.

How do you query elements in nested shadow roots?

Asha still wants every Add button at once. She needs a search that steps into each shadow root it meets. People call that a deep query. Here it is, as a function called findAllDeep():

A deep query that steps into open shadow rootsPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card><tea-panel></tea-panel><tea-gift>Gift box</tea-gift> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script src="tea-gift.js"></script><script>  function findAllDeep(selector, root = document) {    const found = [];    for (const element of root.querySelectorAll("*")) {      if (element.matches(selector)) found.push(element);      if (element.shadowRoot) found.push(...findAllDeep(selector, element.shadowRoot));    }    return found;  }   for (const button of findAllDeep("button")) {    console.log(`${button.textContent} for ${button.getRootNode().host.textContent}`);  }</script>
ResultLoading…
  • Lines 1 to 3 are a card, the panel, and a gift box. In the tea-gift.js tab, line 4 makes the gift's root closed. Line 5 gives it a Wrap button.
  • Line 11 goes through every element in one tree. querySelectorAll("*") lists them all, in the order they appear.
  • Line 12 keeps the elements that match the selector.
  • Line 13 checks for an open shadow root. If there is one, the function searches it the same way, and adds what it finds.
  • Lines 18 to 20 print each button, and the text of its host. getRootNode().host is the card the button lives in.

The console prints Add for Green tea and Add for Oolong. The search went two roots deep: into the panel's root, and from there into Oolong's. A function that calls itself like line 13 does is called recursion. Each call handles one tree. web.dev uses the same idea to list every custom element on a page.

The gift box shows a Wrap button in the result. It isn't in the list. Its root is closed, so gift.shadowRoot is null, as lesson 6.2 showed. No helper can step into a closed root from outside. Try sorting these:

Can findAllDeep() reach it?
  • A button the page wrote
  • The Add button in the Green tea card's open shadow root
  • The Add button of the card inside the panel's shadow root
  • The Wrap button in the gift box's closed shadow root
  • The Add button of a card that sits inside the gift box's closed root
  • A button the page put inside the gift box, shown in its slot
  • The parts the browser puts inside an <input>
Try it yourself
0 of 7 correct

Sort each button or part by whether the deep query finds it.

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

Two cards surprise people. A closed root hides everything behind it, even an open root inside it. But a button the page slots into the gift is still found, because the page wrote it.

What a deep query costs

  • Work. Line 11 lists every element of every open tree, and line 12 checks each one. The bigger the page, the more work each search does. Run it when you need it, not on every key press or scroll.
  • Coupling. It reads other components' insides. If Ravi renames his button, or closes his root, Asha's code breaks, and nothing warns her. A component's public API is made to stay the same, as lesson 5.4 showed. Ask the component first.

So who needs deep queries? Tools do. Nolan Lawson found focus trap libraries that missed the controls inside shadow roots, because they used querySelectorAll(). Test tools search open roots for you: Playwright's locators do, except in closed roots. The testing stage, Testing, tooling, and publishing, covers them.

MDN states the rule this helper works around: document.querySelectorAll() doesn't find elements in shadow DOM.

How do you walk the composed tree?

findAllDeep() visits elements in a set order. What order is it? Here is a walk that prints every node it passes, shadow roots too, with a dash for each level down:

Walking the composed tree, one line per nodePop out in the code editor (opens in a new tab)HTML
<main>  <tea-card><b>Oolong</b></tea-card>  <p>Ask about gift boxes.</p></main> <script src="tea-card.js"></script><script>  function walk(node, depth = 0) {    console.log("- ".repeat(depth) + (node.localName ?? "#shadow-root"));    if (node.shadowRoot) walk(node.shadowRoot, depth + 1);    for (const child of node.children) walk(child, depth + 1);  }   walk(document.querySelector("main"));</script>
ResultLoading…
  • Line 2 is the card from before, with a bold b the page wrote inside it.
  • Line 9 prints a dash for each level, then the node's tag name. A shadow root has no tag name, so it prints #shadow-root.
  • Line 10 walks a host's shadow root first.
  • Line 11 then walks the node's own children. children lists elements only.
  • Line 14 starts at main.

The console prints eight lines: main, - tea-card, - - #shadow-root, - - - h3, - - - - slot, - - - button, - - b, and - p.

The walk's order, one card per line, numbered 1 to 8 and indented by depth: main, tea-card, #shadow-root, h3, slot, button, b, p. Notes on the right: tea-card, the host; #shadow-root, its shadow tree comes first; b, then the card's own child; p, then the card's next sibling.1main2tea-card3#shadow-root4h35slot6button7b8pthe hostits shadow tree comes firstthen the card's own childthen the card's next sibling
The card's shadow tree comes right after the card. The card's own child, b, comes after that, still under the card. In the flat tree, b would sit in the slot instead.

Look at b. The page wrote it inside the card, so it's the card's own child. The walk reaches it after everything in the card's shadow root. The DOM Standard names this order shadow-including tree order:

  1. Visit a node.
  2. If it's a host, walk its shadow tree right away.
  3. Then walk its own children, the same way.

findAllDeep() keeps this order too. Line 13 searches a host's root as soon as line 11 reaches the host, before the loop moves on to the host's children.

This isn't the flat tree from lesson 8.2. The flat tree puts b in the card's slot, where the browser draws it. The composed tree keeps b under the card, where the page wrote it.

Real-life analogyTaking stock, stall by stall

Each evening, Ravi takes stock in the food hall. At each stall, he counts the stall's own shelves first. Then he counts the cups customers left at its counter. Then he moves on to the next stall.

In real life: Reaching a stall
In JavaScript: Visiting a host, tea-card
In real life: Counting the stall's own shelves first
In JavaScript: Walking its shadow tree, line 10
In real life: Then the cups customers left at its counter
In JavaScript: Walking its own children, like b, line 11
In real life: Moving on to the next stall
In JavaScript: The next sibling, p

Can a TreeWalker walk into shadow roots?

No. document.createTreeWalker() makes a TreeWalker, an object that steps through a tree node by node, in the same order. It never steps into a shadow root. To cover shadow roots, start a new one in each root. Nolan Lawson used one in his arrow key library, with extra code for shadow roots. Exercise 2 tries one. MDN covers its options.

Why it matters: a list in this order follows how the page is built. Each component comes first, then its insides, then what the page put in it. That makes a printout of a page easy to read.

Does closest() work across shadow roots?

No. closest() checks an element, then each parent, and gives the first that matches a selector. Inside a shadow root, the climb ends at the root, as lesson 6.3 showed. In lesson 9.1, closest() from the host never looked down either.

Going up, there's a way out: every shadow root has a host. So climb with closest(), and when it stops, jump to the host and climb again. Pick a selector, and compare the two:

Playground: how far does each one climb?
closest() and closestDeep() from the same buttonPop out in the code editor (opens in a new tab)HTML
<main class="menu">  <tea-panel></tea-panel></main> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script>  function closestDeep(selector, element) {    for (let node = element; node; node = node.getRootNode().host) {      const match = node.closest(selector);      if (match) return match;    }    return null;  }   const selector = ".menu";  const panel = document.querySelector("tea-panel");  const add = panel.shadowRoot.querySelector("tea-card").shadowRoot.querySelector("button");  console.log("closest():", add.closest(selector)?.localName ?? null);  console.log("closestDeep():", closestDeep(selector, add)?.localName ?? null);</script>
ResultLoading…
Try it yourself
Out of two shadow roots

closest() stops at the top of the card's shadow root and gives null. closestDeep() climbs out to the card, then out to the panel, and finds main on the page.

Only line 16 changes. Both searches start from the Add button inside the card inside the panel.
  • Line 9 starts at the element. After each try, it steps to node.getRootNode().host, the host of the tree it just searched.
  • Line 10 runs closest() in that tree. Line 11 gives back a match.
  • On the page, the root is the document. It has no host, so line 9 gets undefined and the loop ends. Line 13 gives null.
  • Line 18 finds the Add button inside the card inside the panel. Lines 19 and 20 compare both searches.

With .menu, the console prints closest(): null and closestDeep(): main. With tea-panel and tea-card, closest() gives null again, and closestDeep() finds each host. With button, both print button: closest() checks the element itself first.

Real-life analogyLooking for a manager

A customer asks Ravi for a manager. He looks around his stall first. There's no manager there, so he steps out through the stall's front into the hall, and looks again. Stepping out needs no floor plan.

In real life: Looking around the stall
In JavaScript: closest() in one tree
In real life: Stepping out through the stall's front
In JavaScript: node.getRootNode().host
In real life: Looking around the hall
In JavaScript: closest() again, from the host
In real life: Anyone can step out, even from a private stall
In JavaScript: It works from inside a closed root too

Cory LaViska, who made Shoelace, wrote the same climb. He used it to find the nearest lang attribute, even outside the shadow root. A few more facts:

  • Climbing out never reads shadowRoot, so a closed root can't stop it. A component's own code can climb out of its closed root. Exercise 5 tries it.
  • Pass an element. A text node has no closest(), so start from its parentElement.
  • Inside a component, closestDeep("[lang]", this) reads a setting from wherever the component is placed.

How do you read a selection inside shadow DOM?

A selection is the text the reader highlights. getSelection() gives the page's Selection object. Code often reads it with getRangeAt(0). A range has a start and an end. Each is a node and an offset: a count of letters in text, or of children in an element. Selection and Range covers the basics.

What happens when the selection starts on the page and ends inside a component? Here is a tasting note with its words in a shadow root. The Select button selects from "tea" into "Floral". Then the page reads the selection three ways:

Reading a selection that ends inside a shadow rootPop out in the code editor (opens in a new tab)HTML
<p>Oolong tea: <tea-note></tea-note></p><button id="select">Select</button><button id="read">Read</button> <script src="tea-note.js"></script><script>  const note = document.querySelector("tea-note");  const show = (node, offset) => (node.data ? `"${node.data}"` : node.localName) + ` at ${offset}`;  const print = (label, range) =>    console.log(`${label}: ${show(range.startContainer, range.startOffset)} to ${show(range.endContainer, range.endOffset)}`);   function read() {    const selection = getSelection();    if (selection.rangeCount === 0) return console.log("Nothing is selected.");    print("getRangeAt(0)", selection.getRangeAt(0));    print("getComposedRanges()", selection.getComposedRanges()[0]);    print("With the note's root", selection.getComposedRanges({ shadowRoots: [note.shadowRoot] })[0]);  }   document.querySelector("#select").addEventListener("click", () => {    const words = document.querySelector("p").firstChild;    const noteWords = note.shadowRoot.querySelector("i").firstChild;    getSelection().setBaseAndExtent(words, 7, noteWords, 6);    read();  });  document.querySelector("#read").addEventListener("click", read);</script>
ResultLoading…
  • In the tea-note.js tab, line 5 puts the note's words in its shadow root.
  • Line 8 turns one end into words: a text node's text in quotes, or an element's tag name, then the offset. Lines 9 and 10 print a range's start and end.
  • Line 14 stops early when nothing is selected. Lines 15, 16, and 17 read the selection three ways.
  • Line 23 makes the selection with setBaseAndExtent(). It starts at offset 7 of Oolong tea: , just before the "t". It ends at offset 6 of the note's words, just after "Floral".

Press Select. The selection runs from "tea" to "Floral", and the console prints three lines:

  1. getRangeAt(0): "Floral and sweet." at 6 to "Floral and sweet." at 6
  2. getComposedRanges(): "Oolong tea: " at 7 to p at 2
  3. With the note's root: "Oolong tea: " at 7 to "Floral and sweet." at 6

Chrome's getRangeAt(0) gave an empty range inside the note. It lost the start completely. MDN warns about this: getRangeAt() doesn't know about shadow roots, and what it returns differs between browsers.

getComposedRanges() is the method made for this. It returns an array of StaticRange objects: ranges that don't update when the page changes. Without options, it can't show nodes inside a shadow root. So the end moves out to the note's parent, just after the note: p at 2. The p's first child is the text, the second is the note, and offset 2 comes after both. With { shadowRoots: [note.shadowRoot] }, the range ends where the selection does.

The page's text, Oolong and tea:, then a window called shadow root holding the note's words, Floral and and sweet. Below, four bars. The selection runs from tea: to the end of Floral. getRangeAt(0) is a thin mark after Floral, labelled empty. getComposedRanges() runs from tea: to the end of the note. getComposedRanges with the note's shadow root runs from tea: to the end of Floral.Oolongtea:shadow rootFloraland sweet.inside tea-notethe selectiongetRangeAt(0)emptygetComposedRanges()getComposedRanges({ shadowRoots: [note.shadowRoot] })
The reader's selection runs from tea: into Floral. Without the note's root, getComposedRanges() ends at the edge of the note. With it, the range ends where the selection does.

Read each row across: what the page calls, then where its range starts and ends.

One selection, read three ways in Chrome
What the page callsWhere the range startsWhere the range ends
getRangeAt(0)"Floral and sweet." at 6, inside the note.The same spot. The range is empty.
getComposedRanges()"Oolong tea: " at 7, in the page's text.p at 2, in the p, just after the note.
getComposedRanges({ shadowRoots: [note.shadowRoot] })"Oolong tea: " at 7, in the page's text."Floral and sweet." at 6, inside the note.
Real-life analogyA delivery that ends inside a stall

A delivery starts at the hall's door and ends at a shelf inside the tea stall. On the hall's own map, the route can only end at the stall's front. Hand over the stall's floor plan, and it ends at the right shelf.

In real life: The delivery's route
In JavaScript: The selection
In real life: The hall's map, with no plan for the stall
In JavaScript: getComposedRanges() with no roots
In real life: The route ends at the stall's front
In JavaScript: The end moves to p at 2, after the note
In real life: Handing over the stall's floor plan
In JavaScript: { shadowRoots: [note.shadowRoot] }

Selecting with the mouse

Now drag across the words yourself, from "tea" into "Floral", and press Read. The start depends on where you begin. But the ends follow a pattern. The first line now ends at "Oolong tea: " at 12, the end of the page's own text: getRangeAt(0) cut the note out. The second still ends at p at 2. The third ends inside "Floral and sweet.". So in Chrome, getRangeAt(0) even changes with how the selection was made. Press Read with nothing selected, and it prints Nothing is selected.

A few rules for passing roots:

  • Pass the roots your code may see. A component reading a selection inside itself passes its own root, even a closed one. The page can't pass a closed root: its shadowRoot is null.
  • The first version of the Selection API took the roots directly: getComposedRanges(note.shadowRoot). Chrome reads that as no roots, so the end stops after the note. Exercise 4 fixes it.
  • The array holds one range. The spec expects only one.
  • In Safari, setBaseAndExtent() doesn't accept a node inside a shadow root. So in Safari, drag with the mouse instead of pressing Select.

Why it matters: code that reads selections, like an editor or a highlighter, needs both ends. With components on the page, only getComposedRanges() gives ends you can trust.

Counting cups across the kit's cards

Ravi wants a quick check while he builds the menu page: how many cups is each quantity set to? Since lesson 9.2, each kit card keeps a tea-quantity in its shadow root. And one card sits inside Today's special. So the kit gets a helper file, tea-kit/deep.js, with this lesson's findAllDeep() and closestDeep(). Open its tab: lines 5 to 12 and 15 to 21 are the two functions from above.

Counting every quantity, even inside Today's specialPop out in the code editor (opens in a new tab)HTML
<tea-card name="Green tea" price="4"></tea-card><tea-panel><span slot="heading">Oolong</span></tea-panel><button id="count">Count cups</button> <script type="module">  import "./tea-kit/index.js";  import { closestDeep, findAllDeep } from "./tea-kit/deep.js";   document.querySelector("#count").addEventListener("click", () => {    console.log("querySelectorAll:", document.querySelectorAll("tea-quantity").length);    for (const quantity of findAllDeep("tea-quantity")) {      const where = closestDeep("tea-panel", quantity) ? "Today's special" : "Menu";      console.log(`${where}: ${quantity.value}`);    }  });</script>
ResultLoading…
  • Line 1 is a kit card. Line 2 is the kit's panel, with Oolong as its heading. Line 3 is a Count cups button.
  • Line 6 loads the kit. Line 7 imports the two helpers.
  • Line 10 counts quantities the usual way. Line 11 finds them with findAllDeep().
  • Line 12 asks closestDeep() whether a quantity sits inside a panel. Line 13 prints where it is, and its value, the number of cups.

Press Count cups. The console prints querySelectorAll: 0, Menu: 1, and Today's special: 1. Now press + twice on the Oolong card, and press Count cups again. The last line is now Today's special: 3.

The search found a quantity two roots deep: in Oolong's root, which sits in the panel's root. And closestDeep() climbed out of both to find the panel.

This check reaches into the cards, though. If the card stops using tea-quantity, it breaks. For the shop's real cart, use the card's public tea-add event from lesson 9.2. It carries the tea and the number of cups. Keep deep queries for checks like this one, for tests, and for tools.

Common mix-ups

  • "document.querySelector() finds elements inside components." No. It searches the page's tree only. Start at each open shadowRoot, or use a deep query.
  • "getRootNode() always gives the document." No. Inside a component, it gives the shadow root. A node that isn't on the page gives the top of its own tree.
  • "A deep query can reach every component." No. Closed roots stay hidden, and so does everything behind them, even open roots.
  • "closest() climbs out of a shadow root." No. It stops at the root. Climb out through getRootNode().host.
  • "The composed tree is the flat tree." No. The composed tree keeps slotted children under their host. The flat tree puts them in their slots.
  • "A TreeWalker walks into shadow roots." No. It stays in one tree. Start a new one in each root.
  • "getSelection().getRangeAt(0) shows what's selected inside components." No. Its answer differs between browsers. Chrome gave an empty range for one selection and a cut-short one for another.
  • "getComposedRanges(root) shows the inside of that root." No. Pass an options object: { shadowRoots: [root] }. Chrome reads a bare root as no roots at all.

Practice exercises

For each one, ask which tree each node is in, and whether your code may step into it.

Exercise 1 · Warm-upA card that isn't on the page

The card is made but never added to the page. What does the console print?

<script src="tea-card.js"></script><script>  const card = document.createElement("tea-card");  const add = card.shadowRoot.querySelector("button");  console.log(add.getRootNode({ composed: true }).localName);</script>
ResultLoading…

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

    Exercise 2 · Warm-upA TreeWalker on the walk's page

    Which elements does the walker visit, in order? Compare with the walk's eight lines.

    <main>  <tea-card><b>Oolong</b></tea-card>  <p>Ask about gift boxes.</p></main> <script src="tea-card.js"></script><script>  const walker = document.createTreeWalker(document.querySelector("main"), NodeFilter.SHOW_ELEMENT);  const names = [];  while (walker.nextNode()) names.push(walker.currentNode.localName);  console.log(names.join(", "));</script>
    ResultLoading…

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

      Exercise 3 · PracticeCount every button, deep

      Change the page so it counts every button a deep query can reach. What does the fixed page print?

      <button>Order</button><tea-card>Green tea</tea-card><tea-panel></tea-panel><tea-gift>Gift box</tea-gift> <script src="tea-card.js"></script><script src="tea-panel.js"></script><script src="tea-gift.js"></script><script>  console.log(document.querySelectorAll("button").length);</script>
      ResultLoading…

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

        Exercise 4 · PracticeThe old way of passing a root

        The page should print where the selection really ends. Fix line 10. What does the fixed page print?

        <p>Oolong tea: <tea-note></tea-note></p><button id="select">Select</button> <script src="tea-note.js"></script><script>  const note = document.querySelector("tea-note");  document.querySelector("#select").addEventListener("click", () => {    const noteWords = note.shadowRoot.querySelector("i").firstChild;    getSelection().setBaseAndExtent(document.querySelector("p").firstChild, 7, noteWords, 6);    const [range] = getSelection().getComposedRanges(note.shadowRoot);    console.log(range.endContainer.nodeName, range.endOffset);  });</script>
        ResultLoading…

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

          Exercise 5 · ChallengeClimbing out of a closed root

          The gift's root is closed. Its constructor looks for the nearest .menu from its own Wrap button. What does the console print?

          <main class="menu">  <tea-gift>Gift box</tea-gift></main> <script>  function closestDeep(selector, element) {    for (let node = element; node; node = node.getRootNode().host) {      const match = node.closest(selector);      if (match) return match;    }    return null;  }   class TeaGift extends HTMLElement {    constructor() {      super();      const root = this.attachShadow({ mode: "closed" });      root.innerHTML = "<slot></slot><button>Wrap</button>";      const wrap = root.querySelector("button");      console.log(closestDeep(".menu", wrap)?.localName ?? null);    }  }  customElements.define("tea-gift", TeaGift);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeHow deep is each + button?

            Write depth(node): how many shadow roots sit between a node and the page. The page finds both + buttons in the kit. What does your page print?

            <tea-card name="Green tea" price="4"></tea-card><tea-panel><span slot="heading">Oolong</span></tea-panel> <script type="module">  import "./tea-kit/index.js";  import { findAllDeep } from "./tea-kit/deep.js";   function depth(node) {    return 0;  }   console.log(findAllDeep("#more").map(depth).join(", "));</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask which tree the code starts in, and which way it moves: down, or up.

              The composed tree quiz · 8 questionsScore: first tries count
              1. Question 1 of 8A button sits in a tea card's open shadow root, and the card is on the page. What does button.getRootNode() give?

                Choose an answer to see the explanation.

              2. Question 2 of 8A p was made with document.createElement("p") and never added anywhere. What does p.getRootNode() give?

                Choose an answer to see the explanation.

              3. Question 3 of 8A hint inside a shadow root needs the element with id="tip" in its own tree. Which line finds it?

                Choose an answer to see the explanation.

              4. Question 4 of 8A page holds a card with an Add button in its open root, and a gift box with a Wrap button in its closed root. How many buttons does findAllDeep("button") return?

                Choose an answer to see the explanation.

              5. Question 5 of 8In the walk, what does the next line print, right after - - - button?

                Read the code, then predictHTML
                <main>
                  <tea-card><b>Oolong</b></tea-card>
                  <p>Ask about gift boxes.</p>
                </main>
                
                <script src="tea-card.js"></script>
                <script>
                  function walk(node, depth = 0) {
                    console.log("- ".repeat(depth) + (node.localName ?? "#shadow-root"));
                    if (node.shadowRoot) walk(node.shadowRoot, depth + 1);
                    for (const child of node.children) walk(child, depth + 1);
                  }
                
                  walk(document.querySelector("main"));
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 8Inside the panel's card, add.closest(".menu") runs on the Add button. The panel sits in <main class="menu">. What does it give?

                Choose an answer to see the explanation.

              7. Question 7 of 8A selection starts in the page's text and ends inside the note's shadow root. Where does getComposedRanges(), with no options, end its range?

                Choose an answer to see the explanation.

              8. Question 8 of 8Why read a selection with getComposedRanges() instead of getRangeAt(0)?

                Choose an answer to see the explanation.

              Key takeaways

              • Every search stays in the tree it starts in. Each shadow root is a tree of its own.
              • getRootNode() gives the shadow root inside a component, the document on the page, and the top of its own tree for a node that isn't on the page.
              • { composed: true } climbs out through each host. Use this.getRootNode() to search your own tree.
              • A deep query steps into each open shadowRoot. Closed roots, and all behind them, stay hidden.
              • Deep queries cost work and tie you to other components' insides. Prefer their public API.
              • The composed tree's order visits a host, then its shadow tree, then its own children. It isn't the flat tree.
              • closest() stops at a shadow root. closestDeep() climbs out through each host.
              • Read selections with getComposedRanges({ shadowRoots: [...] }), not getRangeAt(0).

              Remember the one-liner.
              Step down through open shadowRoots, climb up through getRootNode().host, and name the roots you want to see.

              Sources

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

              Coming next: Building a tabs component, the first lesson of module 10. Start a tabs component: its markup, slots, and the attributes and properties it offers.

              CompleteFrontend Clear concepts. Working examples.