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.
- 01Read a component in DevToolsFind its shadow root and badges in the Elements panel, and use
$0on an element inside a shadow root. - 02Find the class behind a tagUse
$0.constructor,customElements.get(), andgetName(), jump to the code, and tell a waiting tag from a broken one. - 03Trace 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:
<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>- 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.jstab. - Line 5 goes through every tag with a
nameattribute. - Line 6 prints three answers for each tag: its name, whether it matches
:defined, and its class.constructoris 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.
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
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-elementbadge next to every tag with a hyphen. Click it to open the tag's class in the Sources panel. - A
slotbadge next to each element shown in a slot, and arevealbadge 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:
<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>- 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-rootline 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
slotbadge next to a child. It went to no slot, so the page doesn't show it. Itsslotattribute may name a slot the shadow root doesn't have, or the root has no default slot. #shadow-root (closed)in the panel, butnullfrom$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:
$0.className // "tabs"
$0.getRootNode().host.localName // "tea-tabs"
$("div.tabs") // null
$("div.tabs", $0.getRootNode()) === $0 // true- Line 1 gives
tabs.$0really is the row inside the shadow root. - Line 2 climbs out.
getRootNode()gives the shadow root the row lives in, andhostis the element that holds that root:tea-tabs. Lesson 9.4 taughtgetRootNode(). - Line 3 gives
null.$()is the Console's short way to writedocument.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 givestrue.
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:
$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 isTeaTabs. - Line 2 asks the registry, the page's list of defined names.
customElements.get()gives the class for a name, orundefined. It's the same class, so the line givestrue. - 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 givesnull. - 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.
$0.constructor starts from the element you selected. get() starts from the name, and getName() goes back from the class to the name.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()givesundefined
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:
<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>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.
Read the answers like this:
- Your class, and
:definedis 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
:definedis false. The constructor threw during the upgrade. The tag staysprecustomizedfor 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:
<tea-label name="Green tea"></tea-label><script src="tea-label.js"></script>- Line 1 is the label. Line 2 loads its class.
- In the
tea-label.jstab, line 3 isdebugger;, at the start ofconnectedCallback(). 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:
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.
<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>- In
tea-label.js, line 2 observesname. 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.
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
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:
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.
| What Chrome prints | What it means | Where to look |
|---|---|---|
NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': the name "tea-label" has already been used with this registry | define() 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 registry | One 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 name | The 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 constructor | new 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 attributes | The 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 attachShadow | This 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:
<script> class TeaLabel extends HTMLElement {} customElements.define("tea-label", TeaLabel); customElements.define("tea-label", class extends HTMLElement {});</script>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.
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:
<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>- In
tea-card.js, line 3 throws insideconnectedCallback(). - 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.
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.
<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>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().
Here are the five, with the tool that finds each one:
- The price won't change. The Console shows that
observedAttributesisundefined. 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
amountproperty, 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
precustomizedand 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.shadowRootshould give it." No. Code in the Console runs like page code, so a closed root givesnull. 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.
What does the console print?
<teabadge>Sale</teabadge>
<script>
const tag = document.querySelector("teabadge");
console.log(tag.constructor.name, tag.matches(":defined"));
</script>HTMLUnknownElement true. teabadge can't be a custom element, so the browser makes an unknown element. Unknown elements are defined, so :defined matches, even though no class ever runs.
What are the two lines this code prints?
class TeaCup extends HTMLElement {}
console.log(customElements.getName(TeaCup));
customElements.define("tea-cup", TeaCup);
console.log(customElements.getName(TeaCup));null, then tea-cup. Line 2 asks about a class the registry doesn't know, so it gives null. After line 3 defines it, line 4 gets its name back.
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><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>In tea-timer.js, line 2 becomes static observedAttributes = ["seconds"];. HTML keeps attribute names in lowercase, so the list must too. Now a click prints seconds: null to 30: the timer had no seconds attribute before.
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><p>Leaf and Kettle</p><script src="tea-card.js"></script><script> window.addEventListener("error", (event) => { event.preventDefault(); console.log("Caught:", event.error.message); }); document.body.append(document.createElement("tea-card"));</script>The listener on lines 4 to 7 hears the reported error and prints Caught: The card has no tea. preventDefault() marks it as handled, so Chrome's own Console no longer lists it as Uncaught. This site's Result hears every reported error before your listener does, so its error box still shows it.
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>set selectedIndex, the setter on line 83. Under it come #choose, #onClick, and the tab row's click listener: the whole path of the click.
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>ready: false. define() put tea-card in the registry, so whenDefined() resolves. But this card's upgrade failed, so it stays precustomized and doesn't match :defined. Check each tag, not only the name.
Check your understanding
For each question, think about which of the four questions it belongs to, and which tool answers it.
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.
Question 2 of 7
$0.constructor.namegivesHTMLElementfor a<tea-lable>tag. What does that tell you?Choose an answer to see the explanation.
Question 3 of 7Something keeps changing the tabs'
selectedattribute. Which breakpoint pauses on the code that changes it?Choose an answer to see the explanation.
Question 4 of 7What does this
try...catcharoundappend()print?Read the code, then predictclass 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.
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.
Question 6 of 7
customElements.get("tea-label")givesundefined, yet the<tea-label>inside a shadow root works. How can that be?Choose an answer to see the explanation.
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-rootline orslotbadge is a clue too. $0.constructor,customElements.get(), andgetName()find the class. With:defined, they tell a waiting tag from a broken one.- Pause in a callback with a line breakpoint,
debugger;, ordebug(). 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...catcharoundappend()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:
- Open Chrome DevTools, Chrome for Developers.
- Badges reference, Chrome for Developers.
- Preferences: Show user agent shadow DOM, Chrome for Developers.
- Console utilities API reference, Chrome for Developers.
- Console features reference: Select JavaScript context, Chrome for Developers.
- Console features reference: Inspect functions, Chrome for Developers.
- CustomElementRegistry: get() method, MDN.
- CustomElementRegistry: getName() method, MDN.
- Element: customElementRegistry property, MDN.
- Pause your code with breakpoints, Chrome for Developers.
- JavaScript debugging reference, Chrome for Developers.
- Console API reference: console.trace(), Chrome for Developers.
- CustomElementRegistry: define() method, Exceptions, MDN.
- Element: attachShadow() method, Exceptions, MDN.
- Web IDL Standard: DOMException names, WHATWG.
- DOM Standard: Create an element, WHATWG.
- HTML Standard: Upgrade an element, WHATWG.
- Catching errors thrown from connectedCallback, Nolan Lawson.
- Handling properties in custom element upgrades, Nolan Lawson.
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.