completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Debugging web components

Learn debugging web components in Chrome DevTools: inspect shadow roots, find an element's class, pause in lifecycle callbacks, and decode common errors.

By the end, you can
  • 01
    Read a component in DevToolsFind its shadow root and badges in the Elements panel, and use $0 on an element inside a shadow root.
  • 02
    Find the class behind a tagUse $0.constructor, customElements.get(), and getName(), jump to the code, and tell a waiting tag from a broken one.
  • 03
    Trace callbacks and decode errorsPause inside lifecycle callbacks, find the code that changed an attribute, and say what each common error means.

How do you debug a web component?

It's Monday morning at Leaf and Kettle. Ravi opens the new menu page. Green tea shows. Black tea doesn't. The console is empty, and the code looks right. Where do you even start?

To debug a web component, ask four questions in order. Is the tag upgraded? Which class runs it? When did its callbacks run? What did the error say? Chrome DevTools has a tool for each one: the Elements panel, the Console, breakpoints in the Sources panel, and the error message itself.

Here is Ravi's page, cut down to the two labels. The page asks the first two questions itself:

Two labels, and the first two questionsPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea"></tea-label><tea-lable name="Black tea"></tea-lable><script src="tea-label.js"></script><script>  for (const tag of document.querySelectorAll("[name]")) {    console.log(tag.localName, tag.matches(":defined"), tag.constructor.name);  }</script>
ResultLoading…
  • Line 1 is the Green tea label. Line 2 should be the Black tea label.
  • Line 3 loads the class. It's in the tea-label.js tab.
  • Line 5 goes through every tag with a name attribute.
  • Line 6 prints three answers for each tag: its name, whether it matches :defined, and its class. constructor is the class an object was made from.

The console prints tea-label true TeaLabel, then tea-lable false HTMLElement. Look at the second name. The letters l and b are swapped. Nobody defined tea-lable, so it waits as a plain HTMLElement. There's no error, because a tag that waits for its class is normal. Lesson 2.4 showed why.

Why it matters: the bug wasn't in the class at all. Two quick questions found it before anyone read the code.

Two columns of cards joined by arrows. On the left, four questions: 1, is it upgraded? 2, which class runs it? 3, when did it run? 4, what went wrong? On the right, the tool for each: the Elements panel, the Console, the Sources panel, and the error message.the questionthe tool1. Is it upgraded?Elements panel2. Which class runs it?Console3. When did it run?Sources panel4. What went wrong?The error message
Ask the four questions in order. Each one has its own tool in DevTools, and the first two take seconds.
Real-life analogyA tea taster's checklist

A tea taster doesn't drink a whole pot to find what's wrong. She follows the same checklist every time. First she looks at the dry leaves. Then she reads the tin. Then she watches the color as it brews, and only then does she taste. Each fault has a sign, if you know where to look.

In real life: Looking at the dry leaves
In JavaScript: The Elements panel: is the tag there, with its shadow root?
In real life: Reading the label on the tin
In JavaScript: The Console: which class runs the tag?
In real life: Watching the color while it brews
In JavaScript: Breakpoints: what happens while the callbacks run
In real life: The note the kitchen writes when a brew goes wrong
In JavaScript: The error message
The main idea

Debugging a web component means asking four questions in order: is it upgraded, which class runs it, when did its callbacks run, and what did the error say. Start with the quick ones. The first two take a few seconds in the Console.

The rest of the lesson takes one question at a time. It uses the tabs you built in lesson 10.1 and lesson 10.2. For breakpoints in any JavaScript, see Debugging in the browser.

What does the Elements panel show for a web component?

Lesson 1.4 opened DevTools for the first time. You right-clicked a tag, chose Inspect, and found its shadow root. Here is what the Elements panel shows for a component, and where you met each part:

  • Your shadow roots, as #shadow-root (open) or #shadow-root (closed), just under the host. The host's own children come after it. Lessons 1.4 and 6.2 showed both.
  • The browser's own shadow roots, like the one inside a video. They show only after you turn on Show user agent shadow DOM, in Settings, then Preferences, then Elements. That was lesson 1.1.
  • A custom-element badge next to every tag with a hyphen. Click it to open the tag's class in the Sources panel.
  • A slot badge next to each element shown in a slot, and a reveal badge to jump back. Lesson 8.2 followed them.

You can choose which badges show. Right-click any element in the DOM tree, and check the ones you want in the Badge settings menu.

Now inspect the tabs from lesson 10.2. Right-click a tab in the Result and choose Inspect:

The tabs to inspectPop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";</script>
ResultLoading…
  • Lines 1 to 8 are the tabs: three buttons, then three panels.
  • Line 11 loads the kit's tea-tabs.js, unchanged. It's in its own tab, and this lesson names its lines.

The Result runs in a frame of its own, inside this page. The Console starts in this page, which DevTools calls top. So before you type the commands below, pick the Result's frame in the Console's JavaScript context menu.

What a missing line tells you

The Elements panel also shows what isn't there. Each gap points to a cause:

  • No #shadow-root line under a tag that should have one. The code that attaches it never ran. Often the tag is still waiting for its class, so check $0.matches(":defined").
  • No slot badge next to a child. It went to no slot, so the page doesn't show it. Its slot attribute may name a slot the shadow root doesn't have, or the root has no default slot.
  • #shadow-root (closed) in the panel, but null from $0.shadowRoot. That's closed mode, not a bug. DevTools can show the root, but code in the Console can't reach it, as lesson 6.2 explained.

Using $0 inside a shadow root

$0 is the element you selected last in the Elements panel. You can select elements inside a shadow root too. Open #shadow-root (open) under <tea-tabs>, and click the div with class="tabs". Then type these lines in the Console:

Questions for an element inside the shadow rootJavaScript
$0.className                          // "tabs"
$0.getRootNode().host.localName       // "tea-tabs"
$("div.tabs")                         // null
$("div.tabs", $0.getRootNode()) === $0  // true
  • Line 1 gives tabs. $0 really is the row inside the shadow root.
  • Line 2 climbs out. getRootNode() gives the shadow root the row lives in, and host is the element that holds that root: tea-tabs. Lesson 9.4 taught getRootNode().
  • Line 3 gives null. $() is the Console's short way to write document.querySelector(). A search from the document doesn't look inside shadow roots, as lesson 6.3 showed.
  • Line 4 gives $() a second argument: where to start. Starting from the shadow root finds the row, so it gives true.

Why it matters: when you click around inside a component, $0.getRootNode().host tells you which component you're in. The Console's helpers, like $0 and $(), are listed in the Console utilities reference. They work only in the Console, not in your page's code.

How do you find a custom element's class?

A tag looks wrong. Is the right code behind it? An old copy? None at all? Every element knows the class it was made from. Select <tea-tabs> in the Elements panel, and ask the Console:

Find the class behind the selected tagJavaScript
$0.constructor.name                     // "TeaTabs"
customElements.get("tea-tabs") === $0.constructor   // true
customElements.getName($0.constructor)  // "tea-tabs"
inspect($0.constructor)                 // opens the class in Sources
console.dir($0.constructor)             // shows [[FunctionLocation]]
  • Line 1 reads the class through constructor. Its name is TeaTabs.
  • Line 2 asks the registry, the page's list of defined names. customElements.get() gives the class for a name, or undefined. It's the same class, so the line gives true.
  • Line 3 goes the other way. customElements.getName() takes a class and gives its name: tea-tabs. For a class that was never defined, it gives null.
  • Line 4 opens the class's code in the Sources panel. inspect() does that for any function you give it.
  • Line 5 lists the class's inner details. One of them, [[FunctionLocation]], is a link to the line where the class is written.

The custom-element badge does the same as line 4, in one click. Use the Console when you also need the answers as values, to compare or to print.

A window called Elements shows <tea-tabs> == $0. An arrow labelled $0.constructor curves from it to a card, class TeaTabs, labelled the class. Below the window is a luggage tag, tea-tabs, labelled the name. An arrow labelled get("tea-tabs") goes from the tag to the class, and an arrow labelled getName(TeaTabs) goes back from the class to the tag.Elements<tea-tabs> == $0$0.constructortea-tabsthe nameclass TeaTabsthe classget("tea-tabs")getName(TeaTabs)
Three ways to the same class. $0.constructor starts from the element you selected. get() starts from the name, and getName() goes back from the class to the name.
Real-life analogyThe kitchen's recipe index

Leaf and Kettle keeps every recipe in one binder. The front page is an index: find a drink's name, and it gives the page. Each recipe also has the drink's name printed at the top. And every cup that leaves the kitchen was made from one recipe.

In real life: The binder's index, from a drink's name to its page
In JavaScript: customElements.get("tea-tabs")
In real life: The name printed at the top of a recipe
In JavaScript: customElements.getName(TeaTabs)
In real life: Asking which recipe made this cup
In JavaScript: $0.constructor
In real life: A drink that isn't in the index yet
In JavaScript: get() gives undefined

What the class says about a broken tag

The class does more than lead you to the code. Read it next to :defined, and it tells you what state the tag is in. Try all four choices. The page is the same each time, except line 1, and the class file in the last choice:

Playground: what the class says about a tag
Four questions about one tagPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea"></tea-label><script src="tea-label.js"></script><script>  const tag = document.querySelector("[name]");  console.log("class:", tag.constructor.name);  console.log(":defined:", tag.matches(":defined"));  console.log("get():", customElements.get(tag.localName)?.name);  console.log("getName():", customElements.getName(tag.constructor));</script>
ResultLoading…
Try it yourself
Your class, and :defined is true

The tag upgraded. Its class is TeaLabel, the registry has that class for tea-label, and getName() gives the name back. Everything agrees, and the Result shows Green tea.

Line 1 changes, and for the last choice the tea-label.js tab too. Lines 5 to 8 ask what you would ask $0 in the Console.

Read the answers like this:

  • Your class, and :defined is true. The tag upgraded, so look for the bug in your own code.
  • HTMLElement. The name is valid, but nothing defined it. Look for a typo, or a file that didn't load.
  • HTMLUnknownElement. The name can't be a custom element, usually because it has no hyphen.
  • Your class, but :defined is false. The constructor threw during the upgrade. The tag stays precustomized for good, as lesson 4.1 showed.

Why it matters: the typo and the missing hyphen print no error at all. The class and :defined still tell them apart. And when the two disagree, trust :defined.

One more case. A tag inside a shadow root with its own registry, from lesson 6.5, isn't in the page's list, so customElements.get() gives undefined. Ask the element's own registry instead: $0.customElementRegistry.get($0.localName).

How do you pause inside a lifecycle callback?

The class is right, and the tag is defined. But the tabs still do something odd. Now you need to watch the code run. A breakpoint is a place where DevTools pauses the page. While it's paused, you can read every value at that moment. It's like pausing a cooking video at the step you want to see.

A breakpoint on a line

Open your own project from lesson 1.4, with the kit's tabs on a page. In the Sources panel, open tea-tabs.js. Click the number of line 72, the first line inside attributeChangedCallback(). A blue marker appears. Now click Black on the page.

DevTools pauses before line 72 runs. The Scope pane shows name, oldValue, and newValue. The Call Stack pane shows how the page got there. Press Resume, or F8, to go on. The JavaScript debugging reference covers each pane.

Right-click a line number for two more kinds. A conditional breakpoint pauses only when a condition you type is true, like name === "selected". A logpoint prints a message without pausing. The Advanced debugging lesson covers both.

The debugger statement

You can also write the breakpoint into the code. A debugger; statement pauses on its line, but only while DevTools is open:

A label that pauses when it connectsPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea"></tea-label><script src="tea-label.js"></script>
ResultLoading…
  • Line 1 is the label. Line 2 loads its class.
  • In the tea-label.js tab, line 3 is debugger;, at the start of connectedCallback(). Line 4 writes the text.

The Result shows Green tea, because DevTools is closed, and line 3 does nothing. Now open DevTools, and press Run again on the Result. The page stops on line 3. The label is still empty, because line 4 hasn't run. Type this.getAttribute("name") in the Console, and it gives Green tea. Press Resume, and the text appears.

Why it matters: debugger; needs no clicks in DevTools, so it works in any page you can edit, like this Result. Take it out before you ship.

Pausing in a method from the Console

No line number handy? debug() pauses on the first line of a function, the next time it runs. It needs the function itself, not its name. A method lives on its class's prototype, and customElements.get() gives you the class:

Pause in the tabs' attributeChangedCallback()JavaScript
const TeaTabs = customElements.get("tea-tabs");
debug(TeaTabs.prototype.attributeChangedCallback);
// Now click Black. DevTools pauses on line 72 of tea-tabs.js.
undebug(TeaTabs.prototype.attributeChangedCallback);
  • Line 1 gets the tabs' class from the registry.
  • Line 2 marks its attributeChangedCallback() method.
  • Line 3 says what happens next. Click Black, and DevTools pauses on line 72 of the class, the method's first line.
  • Line 4, undebug(), takes the mark off.

Who called this callback?

Sometimes you don't need to stop. You need to know who called. console.trace() prints a message, and the call stack under it: the functions that led to this line, newest first. The call stack lesson shows how to read one.

A label that says who changed its namePop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea"></tea-label><button>Black tea</button><script src="tea-label.js"></script><script>  document.querySelector("button").addEventListener("click", function pickBlack() {    document.querySelector("tea-label").setAttribute("name", "Black tea");  });</script>
ResultLoading…
  • In tea-label.js, line 2 observes name. Line 4 prints a trace with the old and the new value. Line 5 shows the new name.
  • On the page, lines 5 to 7 change the name when you click the button. The click function has a name, pickBlack, so traces can show it.

The first trace prints during the upgrade: name: null to Green tea. Under it, the newest place is TeaLabel.attributeChangedCallback (tea-label.js:4:13). The next is line 8 of tea-label.js, the define() call. Now click Black tea. The second trace says name: Green tea to Black tea, and its next place is HTMLButtonElement.pickBlack, in index.html. The stack names who changed the attribute.

Which code changed this attribute?

Back to the tabs. Something sets selected, and you want the line that did it. You don't know which file to look in. A DOM change breakpoint pauses on whatever code changes an element. In the Elements panel, right-click <tea-tabs>, choose Break on, then Attribute modifications. Now click Black.

DevTools pauses on line 83 of tea-tabs.js: this.setAttribute("selected", value), in the selectedIndex setter. The Call Stack reads, from the top: set selectedIndex, then #choose on line 97, then #onClick on line 92, then the tab row's click listener on line 61. Read it from the bottom up, and it tells the story of the click.

Real-life analogyA bell on the shop door

Someone keeps turning the shop's sign from Open to Closed, and Ravi never sees who. So he hangs a bell on the door. The next time it rings, he looks up. He sees who's at the door, and who sent them.

In real life: Hanging a bell on the door
In JavaScript: Break on, Attribute modifications, on <tea-tabs>
In real life: The bell rings
In JavaScript: DevTools pauses on line 83
In real life: Seeing who opened the door, and who sent them
In JavaScript: The Call Stack: the setter, #choose, #onClick
Three cards in a column, joined by downward arrows: line 61, line 83, and line 72 of tea-tabs.js. Next to line 61: the tab row's click listener, where an Event Listener Breakpoint for click pauses. Between the first two, a note: through #onClick() and #choose(). Next to line 83: setAttribute selected, where Break on, then Attribute modifications, pauses. Next to line 72: attributeChangedCallback(), where debug() or a breakpoint on the line pauses.a click on Black runs, top to bottomline 61the tab row's click listenerAn Event Listener Breakpoint for click pauses hereline 83setAttribute("selected", value)Break on, then Attribute modifications, pauses hereline 72attributeChangedCallback()debug() or a breakpoint on the line pauses herethrough #onClick() and #choose()
A click on Black runs these lines of tea-tabs.js, top to bottom. Each kind of breakpoint pauses at a different one. Wherever you pause, the Call Stack shows the lines above it.

Break on has two more choices, and DevTools has two more places to pause:

  • Subtree modifications pauses when a child of the element is added or removed, or a child's content changes.
  • Node removal pauses when the element itself is removed.
  • Event Listener Breakpoints, in the Sources panel, pause in the listeners for an event. Check click, under Mouse, then click a tab. DevTools first pauses on line 61, the tab row's listener.
  • Pause on uncaught exceptions, in the Breakpoints section, pauses on the line that throws. That works even inside a constructor during an upgrade, so it catches the broken tag from the last section in the act.

Each one is in Chrome's guide, Pause your code with breakpoints.

What do common web component errors mean?

Some bugs do print an error. The message looks long, but it's made of parts. Here is one from lesson 3.2, taken apart:

One error message split into four cards, top to bottom, each with a note beside it. NotSupportedError: the kind of error. Failed to execute createElement: the method that failed. On Document: the object it ran on. The result must not have attributes: why it failed.NotSupportedErrorthe kind of errorFailed to execute 'createElement'the method that failedon 'Document'the object it ran onThe result must not have attributeswhy it failed
Six of this lesson's seven errors have these four parts. Read them in order: what kind, which method, on which object, and why.
Real-life analogyA returned parcel's sticker

A parcel comes back to the tea shop with a yellow sticker. It says RETURNED. Then it says what the courier tried, where, and why: delivery failed, at 12 Tea Street, no one at this address. Nobody has to guess what went wrong.

In real life: RETURNED, the kind of sticker
In JavaScript: NotSupportedError
In real life: Delivery failed
In JavaScript: Failed to execute 'createElement'
In real life: At 12 Tea Street
In JavaScript: on 'Document'
In real life: No one at this address
In JavaScript: The result must not have attributes

So this error says: document.createElement() failed, because the new element already had an attribute. The kind is a clue too. In the Web IDL standard, a SyntaxError means a string didn't fit the rules, like a bad name. A NotSupportedError means the browser can't do what you asked.

Here are seven errors from the lessons so far. Read each row across: what Chrome prints, what it means, and where to look.

Common web component errors in Chrome
What Chrome printsWhat it meansWhere to look
NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': the name "tea-label" has already been used with this registrydefine() ran a second time for a name the registry already has.Look for the same component loaded from two addresses, or a page that runs its scripts twice.
NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': this constructor has already been used with this registryOne class was given a second name.Give the second tag its own class. An empty class that extends the first is enough.
SyntaxError: Failed to execute 'define' on 'CustomElementRegistry': "tealabel" is not a valid custom element nameThe name breaks a naming rule, like the hyphen.Start with a lowercase letter, and use only lowercase letters, digits, and hyphens, with at least one hyphen. Those names work in every browser.
TypeError: Failed to construct 'HTMLElement': Illegal constructornew ran on a class the registry doesn't know yet.Call define() before new.
NotSupportedError: Failed to execute 'createElement' on 'Document': The result must not have attributesThe constructor gave the new element an attribute. The message says children instead when it added content.Move that line from the constructor to connectedCallback().
NotSupportedError: Failed to execute 'attachShadow' on 'Element': This element does not support attachShadowThis element can't have a shadow root.Use a custom element, or a host from the list, like div.
NotSupportedError: Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree.attachShadow() ran twice on one element.Attach the root in the constructor, which runs once, not in connectedCallback().

Each one has its own lesson: names and define() in lesson 3.1, the constructor in lesson 3.2, the same file twice in lesson 4.3, and which elements can host a shadow root in lesson 6.1. Now make each one happen:

Playground: make the error happen
One mistake, and its error (an error on purpose)Pop out in the code editor (opens in a new tab)HTML
<script>  class TeaLabel extends HTMLElement {}  customElements.define("tea-label", TeaLabel);  customElements.define("tea-label", class extends HTMLElement {});</script>
ResultLoading…
Try it yourself
The name is taken

Line 4 asks for tea-label again. A registry holds each name once. In a real app, look for the same file loaded from two addresses.

Each choice is a whole page with one mistake. The Result shows the error in its place, as Chrome prints it, with the file and line.

Under each message, the Result names the file and line that threw. In Chrome's Console, click the arrow next to an error to see its stack trace, with the newest place at the top. One more thing about names. The rules for characters after the hyphen differ between browsers, so a name with unusual characters can work in Chrome and throw the SyntaxError in Safari. Lowercase letters, digits, and hyphens work everywhere.

Why do some component errors skip your try...catch?

Ravi wraps his code in a try...catch, so a broken card can't stop the page. Then a card breaks, and his catch never runs:

A try...catch that never catches (an error on purpose)Pop out in the code editor (opens in a new tab)HTML
<p>Leaf and Kettle</p><script src="tea-card.js"></script><script>  try {    document.body.append(document.createElement("tea-card"));    console.log("append() returned");  } catch (error) {    console.log("caught:", error.message);  }</script>
ResultLoading…
  • In tea-card.js, line 3 throws inside connectedCallback().
  • On the page, lines 4 to 9 wrap the work in a try...catch.
  • Line 5 makes a card and adds it to the page. That runs connectedCallback().

The Result shows Error: The card has no tea, from tea-card.js, line 3. The console lists it as Uncaught, and then prints append() returned. The catch on line 7 never ran.

Lesson 3.2 explained why, with a notice board. When the browser calls your code, it catches the error itself and reports it. The error goes to the window's error event and to the console, not to the code that called append(). Nolan Lawson found that the same holds for every lifecycle callback, not only connectedCallback(). So to catch a component's errors in a test, listen on the window. Exercise 4 does it.

A failed upgrade goes quiet

A constructor that throws during an upgrade is reported once, and define() returns as normal. After that, the tag stays broken without another word. It never matches :defined, its callbacks never run, and the browser never tries its constructor again. To find the line, turn on Pause on uncaught exceptions and press Run again. To spot the tag later, look for your class with :defined false, as the playground showed.

When nothing is printed at all

Some faults print nothing. Often, attributeChangedCallback() just never runs. The attribute changes, but the browser only calls you for names in observedAttributes. A name with a capital letter never matches either, because HTML keeps attribute names in lowercase. Lesson 3.4 showed both. One Console line checks the list: customElements.get("tea-price").observedAttributes.

Real-life analogyAn unobserved attribute is a switch wired to nothing

A new switch on the shop wall clicks up and down just fine. But the electrician never wired it to a lamp. You flip it, the switch moves, and the room stays dark. Nothing is broken that you can see.

In real life: Flipping the switch
In JavaScript: setAttribute("amount", "5")
In real life: The wiring plan
In JavaScript: static observedAttributes
In real life: The lamp
In JavaScript: attributeChangedCallback()

Another silent one: a property set before the class was defined hides the setter. Lesson 4.2 showed the fix. The Console spots it with Object.hasOwn($0, "amount"), which gives true when the value sits on the element itself.

Finding five bugs in the tea shop

Time to use the checklist for real. Each page below has one classic fault from this course. Pick a bug and look at the Result. Then find the fault with the tool the note names, and switch to Fixed. Remember to pick the Result's frame in the Console first.

Playground: the tea shop bug hunt
The page with the bugPop out in the code editor (opens in a new tab)HTML
<tea-price amount="4"></tea-price><button>Raise to 5</button><script src="tea-price.js"></script><script>  document.querySelector("button").addEventListener("click", () => {    document.querySelector("tea-price").setAttribute("amount", "5");  });</script>
ResultLoading…
Try it yourself
The price won't change

Press Raise to 5. The price still says 4, and the console stays empty. The Console. Ask the class for its list: customElements.get("tea-price").observedAttributes. It gives undefined. There's no list, so the browser never calls attributeChangedCallback().

Pick a bug, find it with the tool the note names, then switch to Fixed. The files are in their own tabs.

Here are the five, with the tool that finds each one:

  • The price won't change. The Console shows that observedAttributes is undefined. The fix adds the list, as in lesson 3.4.
  • The badge is missing. The error message names createElement() and an attribute. The constructor added a class, which lesson 3.2 forbids.
  • An error from a working label. The place under the message names a second copy, vendor/tea-label.js. Lesson 4.3 met the same clash.
  • The menu counts no teas. A breakpoint in connectedCallback() shows that the parser hasn't read the teas yet. Lesson 3.6 explained why.
  • The price is empty. The Console shows an own amount property, which hides the setter. The upgrade-property pattern from lesson 4.2 fixes it.

Why it matters: none of these needed a guess. Each fault had a sign, and one tool showed it in seconds.

Common mix-ups

  • "Wrap append() in a try...catch to catch a component's errors." No. Errors from lifecycle callbacks are reported to the window, not thrown to the code that called append().
  • "The class is defined, so every tag works." No. If its constructor throws during the upgrade, that one tag stays precustomized and never matches :defined. The registry still has the class.
  • "attributeChangedCallback() is broken." No. Almost always, the attribute is missing from observedAttributes, or it's written there with a capital letter.
  • "Has already been used means my name clashes with an HTML tag." No. HTML never adds tags with a hyphen. Your own define() ran twice, often from the same file at two addresses.
  • "DevTools shows a closed shadow root, so $0.shadowRoot should give it." No. Code in the Console runs like page code, so a closed root gives null. That's closed mode, not a bug.
  • "A typo in a tag name throws an error." No. A valid but unknown name just waits, as a plain HTMLElement. Ask its class to find it.
  • "$() in the Console finds any element on the page." No. It searches from the document, so it skips shadow roots. Give it a start, like $0.shadowRoot.

Practice exercises

Answer first, then use the hints. The pages run live, so you can check yourself.

Exercise 1 · Warm-upA tag with no hyphen

What does the console print?

<teabadge>Sale</teabadge>
<script>
  const tag = document.querySelector("teabadge");
  console.log(tag.constructor.name, tag.matches(":defined"));
</script>

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

    Exercise 2 · Warm-upgetName() before and after

    What are the two lines this code prints?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    class TeaCup extends HTMLElement {}
    console.log(customElements.getName(TeaCup));
    customElements.define("tea-cup", TeaCup);
    console.log(customElements.getName(TeaCup));

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

      Exercise 3 · PracticeWire the timer

      The timer should print a line when you click Make it 30, but it prints nothing. Find the bug in the tea-timer.js tab and fix it. What does your page print when you click?

      <tea-timer></tea-timer><button>Make it 30</button><script src="tea-timer.js"></script><script>  document.querySelector("button").addEventListener("click", () => {    document.querySelector("tea-timer").setAttribute("seconds", "30");  });</script>
      ResultLoading…

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

        Exercise 4 · PracticeCatch the reported error

        Replace the try...catch with a listener that catches the card's error and prints Caught: and its message. What does your page print?

        <p>Leaf and Kettle</p><script src="tea-card.js"></script><script>  try {    document.body.append(document.createElement("tea-card"));    console.log("append() returned");  } catch (error) {    console.log("caught:", error.message);  }</script>
        ResultLoading…

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

          Exercise 5 · ChallengeWho changed selected?

          Set a DOM change breakpoint on the tabs for attribute changes, then click Oolong. Which function is at the top of the Call Stack?

          <tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";</script>
          ResultLoading…

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

            Exercise 6 · ChallengeDefined, but not ready

            The constructor in tea-card.js throws. What does the page print after the error?

            <tea-card></tea-card>
            <script src="tea-card.js"></script>
            <script>
              customElements.whenDefined("tea-card").then(() => {
                const card = document.querySelector("tea-card");
                console.log("ready:", card.matches(":defined"));
              });
            </script>

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

              Check your understanding

              For each question, think about which of the four questions it belongs to, and which tool answers it.

              The debugging quiz · 7 questionsScore: first tries count
              1. Question 1 of 7DevTools shows #shadow-root (closed) under <tea-card>. You select the card and run $0.shadowRoot. What do you get?

                Choose an answer to see the explanation.

              2. Question 2 of 7$0.constructor.name gives HTMLElement for a <tea-lable> tag. What does that tell you?

                Choose an answer to see the explanation.

              3. Question 3 of 7Something keeps changing the tabs' selected attribute. Which breakpoint pauses on the code that changes it?

                Choose an answer to see the explanation.

              4. Question 4 of 7What does this try...catch around append() print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                class TeaCard extends HTMLElement {
                  connectedCallback() {
                    throw new Error("No tea");
                  }
                }
                customElements.define("tea-card", TeaCard);
                try {
                  document.body.append(document.createElement("tea-card"));
                  console.log("added");
                } catch {
                  console.log("caught");
                }

                Choose an answer to see the explanation.

              5. Question 5 of 7The console says the name "tea-label" has already been used with this registry. What usually causes it?

                Choose an answer to see the explanation.

              6. Question 6 of 7customElements.get("tea-label") gives undefined, yet the <tea-label> inside a shadow root works. How can that be?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which call pauses DevTools on the first line of the tabs' attributeChangedCallback()?

                Choose an answer to see the explanation.

              Key takeaways

              • Debug in order: is the tag upgraded, which class runs it, when did its callbacks run, and what did the error say.
              • The Elements panel shows shadow roots and badges. A missing #shadow-root line or slot badge is a clue too.
              • $0.constructor, customElements.get(), and getName() find the class. With :defined, they tell a waiting tag from a broken one.
              • Pause in a callback with a line breakpoint, debugger;, or debug(). Find who changed an attribute with a DOM change breakpoint.
              • Read an error in parts: the kind, the method, the object, and the reason.
              • Errors from lifecycle callbacks are reported to the window, so a try...catch around append() misses them.

              Remember the one-liner.
              Ask four questions in order, and let DevTools answer each: the Elements panel, the Console, a breakpoint, and the error message.

              Sources

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

              Coming next: Styles inside a shadow root, the first lesson of Styling web components. Stage 4 starts with where a component's styles live, and what the page's styles can still reach.

              CompleteFrontend Clear concepts. Working examples.