completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

How elements upgrade when their definition loads

Learn how a custom element upgrade works: which tags define() reaches, what runs, and how to use customElements.upgrade(), whenDefined(), get(), and getName().

By the end, you can
  • 01
    Predict which elements upgrade, and whenTell which tags define() reaches, in what order, and which ones wait until they join the page.
  • 02
    Say what runs during an upgradeThe same element gets your class, then its constructor and callbacks run, and a failed upgrade is never tried again.
  • 03
    Use the registry's other methodsUpgrade elements off the page with customElements.upgrade(), wait with whenDefined(), and look things up with get() and getName().

What is a custom element upgrade?

Ravi's menu page for Leaf and Kettle loads the tea kit last. On a slow phone, the kit can arrive two seconds after the page. Until then, each <tea-label> just shows the words inside it.

Ravi's own script runs first. It grabs a label and adds a click handler to it. Then the kit arrives, and the label changes. Is it still the label his script grabbed? Will his click handler still run?

A custom element upgrade is the moment an element that is already on the page gets its class. The browser keeps the same element, gives it your class, and runs your constructor on it. Then it runs attributeChangedCallback() and connectedCallback(). So the answer to both questions is yes. Here is Ravi's page, with the kit's label loaded two seconds late:

The kit's label arrives two seconds latePop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label> <script type="module">  const waiting = document.querySelector("tea-label");  waiting.addEventListener("click", () => console.log("Clicked"));  console.log("Before:", waiting.constructor.name);   await new Promise((resolve) => setTimeout(resolve, 2000));  await import("./tea-kit/tea-label.js");   console.log("After:", waiting.constructor.name);  console.log("Same element:", waiting === document.querySelector("tea-label"));</script>
ResultLoading…
  • Line 1 is the label, with the words Green tea inside. Nothing has defined tea-label yet.
  • Line 4 keeps the label in a variable called waiting. Line 5 adds a click handler to it.
  • Line 6 prints the name of the label's class: Before: HTMLElement. Every waiting tag is a plain HTMLElement.
  • Line 8 waits two seconds, like a slow network. Line 9 loads the kit's tea-label.js, the second tab, with import(). It loads a file while the page runs, as the Dynamic import lesson shows. The file's last line calls customElements.define().
  • Line 11 prints After: TeaLabel. Line 12 prints Same element: true.

Watch the result. It shows Green tea for two seconds, then Green tea: brew for 3 minutes. Now click the label. The console prints Clicked. The handler from line 5 still works, because nothing was swapped. The browser changed the element in place.

Real-life analogyStaff who start before the uniforms arrive

Leaf and Kettle opens a new shop. On the first morning, the staff work in their own clothes. Customers already know them by name. At noon, the box of uniforms arrives. The manager doesn't hire new people. She hands each person a uniform, and they carry on.

In real life: Staff working in their own clothes
In JavaScript: Tags waiting as plain HTMLElements
In real life: The box of uniforms arriving
In JavaScript: customElements.define() with your class
In real life: Handing each person a uniform
In JavaScript: Upgrading each element, in place
In real life: Customers who already know them by name
In JavaScript: Your references and click handlers
The main idea

An upgrade doesn't make a new element. The browser gives the element that is already there your class, then runs your constructor and callbacks on it. Its place on the page stays. So do its attributes, its children, and every reference to it.

You've seen upgrades from the page's side. Lesson 1.1 showed a tag that waits for its class. Lesson 2.4 showed what a waiting tag looks like. Lesson 3.6 showed that an upgrade runs its callbacks inside define(). This lesson looks from your side, as the author of the class. Which elements will it meet, and what runs on them?

Which elements does customElements.define() upgrade?

When you call define(), the browser looks for elements to upgrade. The HTML Standard calls them upgrade candidates. Its steps for define() pick every element with the new name that is in the document. They look inside shadow roots too. Then they queue an upgrade for each one, in page order.

Which labels does define() reach?Pop out in the code editor (opens in a new tab)HTML
<tea-label>Oolong</tea-label><div id="box"></div><tea-label>Black</tea-label> <script>  const box = document.querySelector("#box");  box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label>";  const loose = document.createElement("tea-label");   class TeaLabel extends HTMLElement {    connectedCallback() {      console.log("Upgraded", this.textContent);    }  }  customElements.define("tea-label", TeaLabel);  console.log("Loose label upgraded:", loose instanceof TeaLabel);</script>
ResultLoading…
  • Lines 1 to 3 are the page: a label, an empty box, and another label.
  • Line 7 gives the box a shadow root: a private tree of its own, as in lesson 1.1. It puts a third label, Green, inside it.
  • Line 8 makes a fourth label with createElement(). It's never added to the page. Call it the loose label.
  • Lines 10 to 14 are the class. Each label prints its text when its connectedCallback() runs.
  • Line 15 registers the class. Line 16 checks the loose label.

The console prints Upgraded Oolong, Upgraded Green, Upgraded Black, and then Loose label upgraded: false. That shows three rules:

  • Page order. The browser walks the page from top to bottom. The spec calls it shadow-including tree order.
  • Shadow roots count. When the walk reaches the box, it goes into the box's shadow root before it moves on. So Green comes second. A closed shadow root is no different.
  • Only the document. The loose label isn't in the document, so define() never sees it. It keeps waiting.
Which labels define() upgrades. The page holds Oolong, a box, and Black, in that order. The box's shadow root holds Green. define() upgrades Oolong first, Green second, and Black third. A loose label outside the page isn't upgraded: it waits.pageOolongupgraded 1st#boxGreenshadow rootupgraded 2ndBlackupgraded 3rdloosenot in the pagewaits
define() walks the page from top to bottom, and goes into a shadow root when it reaches its host. The loose label isn't in the page, so it waits.

Think of the manager with the uniforms. She walks the shop from the door to the back, and steps into each side room as she passes it. Someone on a day off doesn't get a uniform today.

Chrome doesn't search the whole page when you call define(). It keeps a list of waiting elements for each name. CollectCandidates() takes the list for the new name and sorts it into page order.

One element at a time

Each upgrade finishes before the next one starts. The first element's constructor and callbacks all run first. So while one element upgrades, the ones after it are still waiting:

Counting the labels that are readyPop out in the code editor (opens in a new tab)HTML
<tea-label>Oolong</tea-label><tea-label>Green</tea-label><tea-label>Black</tea-label> <script>  class TeaLabel extends HTMLElement {    connectedCallback() {      const ready = document.querySelectorAll("tea-label:defined").length;      console.log(`${this.textContent}: ${ready} of 3 ready`);    }  }  customElements.define("tea-label", TeaLabel);</script>
ResultLoading…
  • Lines 1 to 3 are three labels.
  • Line 8 counts the labels that match :defined right now. :defined matches a custom element once its upgrade has finished.
  • Line 9 prints the label's text and the count.

It prints Oolong: 1 of 3 ready, then Green: 2 of 3 ready, then Black: 3 of 3 ready. When Oolong's callback runs, Green and Black are still plain elements. Domenic Denicola's note on why upgrades exist points out this moment. An element that looks at its neighbor during an upgrade can find it not upgraded yet.

Why it matters: during its own upgrade, a component can't rely on the components after it. Lesson 3.6 met the same problem with a menu and its items.

What happens during a custom element upgrade?

An upgrade is a short list of steps in the HTML Standard, called upgrade an element. Here they are in plain words, for one waiting element:

  1. If the element isn't waiting anymore, stop. No element is upgraded twice.
  2. Mark the element as failed, for now. If a second upgrade of it starts in the middle of this one, step 1 stops it.
  3. Queue a call to attributeChangedCallback() for each attribute the element has. Only the ones in observedAttributes will run.
  4. If the element is in a document, queue a call to connectedCallback().
  5. Mark the element as precustomized, and run your constructor on it.
  6. If the constructor throws, drop the queued calls and stop. The element isn't waiting now, so step 1 stops any later try.
  7. Otherwise, mark the element as custom. Then the queued calls run.

Failed, precustomized, and custom are states from the list in lesson 2.4. A waiting element's state is undefined. While the constructor runs, it's precustomized, so :defined doesn't match yet. Lesson 3.4 showed the order of the attribute calls: the tag's order, each one from null.

How the constructor runs on an element that exists

Step 5 sounds odd. A constructor normally makes a new object. How can it run on one that already exists? The answer is in super().

Before step 5, the browser puts the waiting element on a short list that belongs to your class. The standard calls it the construction stack. Your constructor calls super(), which runs HTMLElement's constructor. That constructor checks the list and finds the waiting element. It gives the element your class's prototype, the object that holds your methods. Then it returns the element, and that becomes this. The standard spells this out in its steps for HTML element constructors. The prototype chain lesson explains prototypes.

Try both choices. The same page upgrades one label, with a constructor that works or one that throws:

Playground: watch one upgrade
One label, upgraded step by stepPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green">Green tea</tea-label> <script>  const waiting = document.querySelector("tea-label");   class TeaLabel extends HTMLElement {    static observedAttributes = ["name"];    constructor() {      super();      console.log("constructor, same element:", this === waiting);      // Nothing goes wrong here.    }    attributeChangedCallback(name, oldValue, newValue) {      console.log("attributeChangedCallback:", oldValue, "to", newValue);    }    connectedCallback() {      console.log("connectedCallback");    }  }  customElements.define("tea-label", TeaLabel);  console.log("define() returned. :defined is", waiting.matches(":defined"));  console.log("instanceof TeaLabel is", waiting instanceof TeaLabel);  customElements.upgrade(waiting);</script>
ResultLoading…
Try it yourself
The upgrade finishes, and the element is custom

The constructor runs on the element that was already on the page. Then attributeChangedCallback() runs for name, then connectedCallback(). All of it happens inside define(). Line 23 asks for a second upgrade, and nothing happens: the element is already custom.

Both choices are the same page. Only line 11 changes. Each run starts in a fresh page, and the console lists what ran, in order.
  • Line 4 keeps the waiting label in waiting.
  • Line 7 watches the name attribute.
  • Line 10 checks that this is the waiting label.
  • Line 11 is the only line that changes. It either does nothing or throws.
  • Lines 20 to 22 register the class, then check the label with :defined and instanceof.
  • Line 23 asks for a second upgrade of the same label.

With a working constructor, five lines print. The constructor says same element: true. Then come attributeChangedCallback: null to Green and connectedCallback, all before define() returns. Line 23 prints nothing, because the label is already custom.

Now pick The constructor throws. The console shows Error: The label broke, but define() doesn't throw. Line 21 still runs and prints :defined is false. The two callbacks never run. And line 23 doesn't try again. Once an upgrade fails, it fails for good.

Look at line 22 in that run. It prints instanceof TeaLabel is true, even though the upgrade failed. The super() call had already given the label its prototype before line 11 threw. So instanceof can't tell you an upgrade worked. :defined can.

The steps of one upgrade, top to bottom. The waiting element's state is undefined. The constructor runs, and this is the same element. As soon as it finishes, the state is custom and :defined matches. Then attributeChangedCallback runs for each watched attribute, then connectedCallback if the element is in a document. If the constructor throws, the upgrade fails, and the element is never tried again.undefinedwaiting on the pageconstructor()this is the same elementcustom:defined matches nowattributeChangedCallback()each watched attributeconnectedCallback()if it's in a documentit throwsupgrade failednever tried again
One upgrade, top to bottom. The element is custom as soon as the constructor finishes, and then the queued callbacks run. If the constructor throws, the upgrade fails for good.
Real-life analogyRe-covering a chair where it stands

The café's armchairs are getting new covers. The upholsterer works on each chair where it stands. She doesn't swap it for another chair, and the coats on it stay put. If the fabric tears halfway, she leaves that chair and never comes back to it.

In real life: The armchair
In JavaScript: The waiting element
In real life: Working on it where it stands
In JavaScript: The constructor running on that element, as this
In real life: The coats left on it
In JavaScript: Its attributes, children, and listeners
In real life: The new cover
In JavaScript: Your class's prototype and methods
In real life: A torn cover, never redone
In JavaScript: A constructor that throws: the upgrade fails for good

Why it matters: your constructor may meet an element that already has attributes, children, and listeners. That's why lesson 3.2 says not to read them there. And keep the constructor simple. If it throws, that element never gets a second chance.

What does customElements.upgrade() do?

define() only looks in the document. But scripts often build elements off the page first, then add them. Those elements can upgrade in two ways:

  • When they join the page. The DOM Standard's insert steps check every element that joins a document. For each one that is still waiting, they try to upgrade it: look up its name, and upgrade it if a class is defined.
  • When you call customElements.upgrade(root). It tries to upgrade root and every element inside it, shadow roots too. It works off the page.

Here a script makes a price before the kit loads, and upgrades it before it joins the page:

Upgrade a price before it joins the pagePop out in the code editor (opens in a new tab)HTML
<p id="shelf">Green tea.</p> <script type="module">  const price = document.createElement("tea-price");  price.setAttribute("amount", "4");   const { TeaPrice } = await import("./tea-kit/tea-price.js");  console.log("After define():", price instanceof TeaPrice);   customElements.upgrade(price);  console.log("After upgrade():", price.textContent);   document.querySelector("#shelf").append(" ", price);</script>
ResultLoading…
  • Line 4 makes a tea-price before the kit has loaded. Line 5 sets its amount.
  • Line 7 loads the kit's tea-price.js, the second tab. It defines tea-price and gives back its class.
  • Line 8 prints After define(): false. The price is off the page, so define() skipped it.
  • Line 10 upgrades it. Line 11 prints After upgrade(): Price: 4.
  • Line 13 adds it to the shelf.

Where did Price: 4 come from? In tea-price.js, attributeChangedCallback() draws the text. During the upgrade, it ran for amount, as step 3 says. connectedCallback() didn't run, because the price wasn't in a document yet. It runs on line 13.

Real-life analogyBuilding a table in the back room

New tables arrive flat-packed. The staff could build each one in the café, in front of customers. Or they can build it in the back room, check that it stands, and carry it out ready.

In real life: The flat-pack box
In JavaScript: An element off the page, still waiting
In real life: Building it in the back room
In JavaScript: customElements.upgrade(element)
In real life: Carrying it into the café
In JavaScript: Adding it to the page, which runs connectedCallback()
In real life: Building it in front of customers
In JavaScript: Letting it upgrade as it joins the page

Why it matters: after upgrade(), the element has your class's methods, even off the page. You can call them before you add it. It never throws, either. It simply skips elements it can't upgrade:

  • Elements that aren't waiting. An element that has upgraded, or whose upgrade failed, is left alone. Line 23 of the steps playground showed it.
  • Names with no class yet. Nothing happens, and nothing is remembered. Call it again after define().
  • Elements from another registry. Browsers now let a shadow root have its own registry, a scoped registry. Stage 3 covers them. customElements.upgrade() skips elements that belong to another one.
  • Elements whose document has no registry. That's the surprise in the next section.

Why doesn't customElements.upgrade() upgrade a template copy?

People ask this on Stack Overflow. They copy a <template>'s content, call upgrade() on the copy, and its elements stay plain. Here is the same thing:

upgrade() skips a template copyPop out in the code editor (opens in a new tab)HTML
<p id="shelf"></p><template id="row"><tea-label name="Green tea" minutes="3"></tea-label></template> <script type="module">  await import("./tea-kit/tea-label.js");  const template = document.querySelector("#row");   const copy = template.content.cloneNode(true);  customElements.upgrade(copy);  console.log("Copy made with cloneNode():", copy.firstElementChild.matches(":defined"));   const imported = document.importNode(template.content, true);  console.log("Copy made with importNode():", imported.firstElementChild.matches(":defined"));  document.querySelector("#shelf").append(imported);</script>
ResultLoading…
  • Line 2 is a template that holds one label.
  • Line 5 loads the kit's label, which defines tea-label.
  • Line 8 copies the template's content with cloneNode(true). Line 9 tries to upgrade the copy.
  • Line 10 prints Copy made with cloneNode(): false.
  • Line 12 copies it with document.importNode() instead. Line 13 prints Copy made with importNode(): true.
  • Line 14 adds that copy to the shelf. It shows Green tea: brew for 3 minutes.

A template's content doesn't belong to the page's document. The browser keeps it in a separate document, made for templates. That document has no window, so it has no registry. A cloneNode() copy stays in that document, as lesson 3.6 showed. And upgrade() skips every element whose registry isn't the one you called it on. These elements have none at all.

importNode() copies the content into the page's document, where the registry is. So its copy is upgraded as it's made. append() works too: it moves the copy into the page, and it upgrades there.

Two documents. On top, the template's own document holds a copy made with cloneNode(). It has no registry, so upgrade() skips the copy. An arrow labelled importNode() or append() leads down to the page's document, which has customElements. There the copy is upgraded.templatecloneNode() copyno registry hereits own documentupgrade() skips itimportNode() or append()pageupgraded copycustomElementsthe page's documentupgraded here
A template's content lives in a document of its own, with no registry. importNode() copies it into the page's document, and append() moves it there. Either way, the copy upgrades in the page.

Documents with no window

The same goes for any document without a window. document.implementation.createHTMLDocument() makes one, and so does DOMParser. Elements made in them stay plain, even when the page has defined their names:

A label made in a draft documentPop out in the code editor (opens in a new tab)HTML
<p id="shelf"></p> <script type="module">  await import("./tea-kit/tea-label.js");  const draft = document.implementation.createHTMLDocument("Draft");  const label = draft.createElement("tea-label");  label.setAttribute("name", "Mint tea");  label.setAttribute("minutes", "5");   customElements.upgrade(label);  console.log("In the draft:", label.matches(":defined"));  document.querySelector("#shelf").append(label);  console.log("On the page:", label.matches(":defined"));</script>
ResultLoading…
  • Line 5 makes an empty document called Draft. It has no window.
  • Line 6 makes a label in it. Lines 7 and 8 give it a name and a time.
  • Line 10 tries to upgrade it. Line 11 prints In the draft: false.
  • Line 12 moves it into the page. Line 13 prints On the page: true.

It's like a chair in an architect's model of the shop. Nobody sits on it until it's in the real shop. Why it matters: custom elements you build in another document stay plain until they join the page. Don't call their methods before then.

Try every place

Now compare all five places at once. The playground makes one label, then calls each step and prints its name:

Playground: where is the label when define() runs?
One label, made in different placesPop out in the code editor (opens in a new tab)HTML
<template><tea-label></tea-label></template><div id="box"></div><script src="tea-label.js"></script> <script>  // A label in the page  const label = document.createElement("tea-label");  document.body.append(label);   console.log("1. define()");  customElements.define("tea-label", TeaLabel);  console.log("2. upgrade()");  customElements.upgrade(label);  console.log("3. append()");  if (!label.isConnected) document.querySelector("#box").append(label);</script>
ResultLoading…
Try it yourself
define() upgrades it

The label is in the document, so define() finds it. It runs the constructor and connectedCallback() before it returns. Then upgrade() has nothing left to do.

Pick where the label is made. Only lines 6 to 8 change. The console shows each step, then the callbacks it ran, so you can see which step upgraded the label.
  • Line 1 is a template. Only the template choice uses it. Line 2 is an empty box.
  • Line 3 loads tea-label.js, the second tab. It makes the class but doesn't call define(). Its constructor and connectedCallback() each print their name.
  • Lines 6 to 8 make the label. They change with your choice.
  • Lines 10 to 15 print each step, then run it: define(), upgrade(), and adding the label to the box if it isn't on the page yet.

Read each row across: where the label is, then what each step does to it.

Which step upgrades the label
Where the label isDoes define() upgrade it?Does upgrade() upgrade it?When does it upgrade?
In the pageYes.It's already upgraded, so nothing happens.Inside define().
In a shadow rootYes.It's already upgraded, so nothing happens.Inside define(), in page order.
Made by a scriptNo.Yes. The constructor runs, but connectedCallback() waits.Inside upgrade(), or when it joins the page.
A template copyNo.No. The copy belongs to the template's document, which has no registry.When it joins the page.
Another documentNo.No. Its document has no window, so it has no registry.When it joins the page.

When does customElements.whenDefined() fulfill?

Lesson 2.2 used whenDefined() from the page's side. It waits for a name, and its promise fulfills with the class. A name that is never defined waits forever. That's why lesson 2.4 raced it against a timer with Promise.race(). As an author, you need one more detail. What is ready when the promise fulfills?

What is ready when whenDefined() fulfillsPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label><tea-label name="Black tea" minutes="4">Black tea</tea-label> <script type="module">  const loose = document.createElement("tea-label");   customElements.whenDefined("tea-label").then((TeaLabel) => {    const labels = [...document.querySelectorAll("tea-label")];    console.log("On the page:", labels.every((label) => label instanceof TeaLabel));    console.log("Off the page:", loose instanceof TeaLabel);  });   setTimeout(() => import("./tea-kit/tea-label.js"), 1000);</script>
ResultLoading…
  • Lines 1 and 2 are two labels on the page.
  • Line 5 makes a third label, off the page.
  • Line 7 waits for tea-label. The promise gives the class, which this code calls TeaLabel.
  • Line 9 checks that every label on the page is a TeaLabel. Line 10 checks the loose one.
  • Line 13 loads the kit's label after one second.

After one second, it prints On the page: true, then Off the page: false.

Here is why. define() queues an upgrade for every candidate, then fulfills the promise. The queued upgrades all run before define() returns. Your then() code runs later still. So by then, every element with that name in the page is upgraded. But the promise is about the name, not about each element. The loose label still waits. If you need it upgraded, call customElements.upgrade() on it.

One promise per name

While a name waits, the registry keeps one promise for it. Every whenDefined() call for that name gets that same promise:

The same promise, until the name is definedPop out in the code editor (opens in a new tab)JavaScript
const first = customElements.whenDefined("tea-cup");
const second = customElements.whenDefined("tea-cup");
console.log(first === second);

customElements.define("tea-cup", class extends HTMLElement {});
console.log(customElements.whenDefined("tea-cup") === customElements.whenDefined("tea-cup"));
  • Lines 1 and 2 ask twice, before tea-cup is defined. Line 3 prints true: it's one promise.
  • Line 5 defines tea-cup. Line 6 asks twice more and prints false. Now each call gets a new promise that has already fulfilled.

Chrome keeps the waiting promises in a map from names to promises. You can see it in its whenDefined(). It's like a crowd at a station watching one departure board. Many components can wait for the same name, and they all wait on that one promise.

How do you check if a custom element is defined?

The registry answers two questions. customElements.get(name) gives the class for a name, or undefined. customElements.getName(class) goes the other way. It gives the name for a class, or null.

Look up a name, then a classPop out in the code editor (opens in a new tab)JavaScript
class TeaLabel extends HTMLElement {}
customElements.define("shop-label", TeaLabel);

console.log(customElements.get("shop-label") === TeaLabel);
console.log(customElements.get("tea-label"));
console.log(customElements.getName(TeaLabel));
console.log(customElements.getName(HTMLElement));
  • Line 2 registers TeaLabel under another name, shop-label. Say a page renamed the kit's tag to avoid a clash.
  • Line 4 prints true. get() gives back the class itself.
  • Line 5 prints undefined. Nothing is called tea-label here.
  • Line 6 prints shop-label. When you only have the class, this is how you learn its tag name.
  • Line 7 prints null. HTMLElement was never defined as a custom element.
Two lookups in the registry. An arrow labelled get(name) goes from the name shop-label to the class TeaLabel. An arrow labelled getName(class) goes back from the class to the name.shop-labelTeaLabelget(name)getName(class)the namethe class
get() turns a name into its class, or undefined. getName() turns a class into its name, or null.
Real-life analogyA phone book that works both ways

The shop keeps a book of its suppliers. Look up a name, and you find their phone number. This book also works the other way. Look up a number, and you find whose it is. If nobody is listed, the book has nothing to show.

In real life: A supplier's name
In JavaScript: A tag name, like shop-label
In real life: Their phone number
In JavaScript: The class, TeaLabel
In real life: Looking up a name
In JavaScript: customElements.get("shop-label")
In real life: Looking up a number
In JavaScript: customElements.getName(TeaLabel)
In real life: Nobody listed
In JavaScript: undefined from get(), null from getName()

getName() always has one answer, because a registry takes each class only once. A second define() with the same class throws, on purpose:

The same class under two names (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
class TeaLabel extends HTMLElement {}
customElements.define("tea-label", TeaLabel);
customElements.define("shop-label", TeaLabel);

Line 3 throws a NotSupportedError. Chrome's message reads this constructor has already been used with this registry. So each class has one name, and getName() can't be unsure.

Checking one element

get() tells you about a name. To ask about one element, use element.matches(":defined"). For a tag with a hyphen, it's true once that element's upgrade has finished. Don't use instanceof for this. The steps playground showed a label whose upgrade failed, where instanceof said true. :defined said false, which was right.

Finding tags that didn't upgrade

Now put it together into a small checking tool. Asha's test page loads the whole kit, but two tags never come to life. One name is spelled wrong. One component's constructor throws. Which is which?

List the tags that didn't upgrade, and whyPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label><tea-prcie amount="4">Price: 4</tea-prcie><tea-cup>A cup</tea-cup><button>Check the page</button> <script type="module" src="tea-kit/index.js"></script><script type="module" src="tea-cup.js"></script><script>  document.querySelector("button").addEventListener("click", () => {    for (const tag of document.querySelectorAll(":not(:defined)")) {      const name = tag.localName;      const why = customElements.get(name) ? "its constructor threw" : "nothing defines this name";      console.log(`${name} didn't upgrade: ${why}`);    }  });</script>
ResultLoading…
  • Lines 1 to 3 are three tags: a kit label, a misspelled tea-prcie, and a tea-cup.
  • Line 6 loads the whole kit through tea-kit/index.js. Line 7 loads tea-cup.js, whose constructor always throws.
  • Line 10 finds every element that doesn't match :defined.
  • Line 12 asks the registry about each name. If there is a class, the name is defined, so the constructor must have thrown. If not, nothing defines the name.
  • Line 13 prints the answer.

Click Check the page. The first line it prints is tea-prcie didn't upgrade: nothing defines this name. The second is tea-cup didn't upgrade: its constructor threw. The label upgraded, so it isn't listed.

The loop works on any page. Open DevTools, click the Console tab, and paste it in:

Paste this into the ConsolePop out in the code editor (opens in a new tab)JavaScript
for (const tag of document.querySelectorAll(":not(:defined)")) {
  const name = tag.localName;
  const why = customElements.get(name) ? "its constructor threw" : "nothing defines this name";
  console.log(`${name} didn't upgrade: ${why}`);
}

These are lines 10 to 14 from above, without the click. Line 4 prints one line for each tag that didn't upgrade. Mind two limits. Run it after the page has loaded, because a tag whose file is still on its way looks like nothing defines it. And it only sees the page's own tree. Tags inside a component's shadow root don't show up.

Common mix-ups

  • "define() upgrades every element with that name." No. It upgrades only the ones in the document, shadow roots included. An element a script made and hasn't added waits until it joins the page, or until you call customElements.upgrade().
  • "An upgrade swaps the element for a new one." No. It's the same object. Your references, listeners, attributes, and children all stay.
  • "customElements.upgrade() works on any element." No. It skips a template's cloneNode() copy, elements from a document with no window, and elements from another registry. Use importNode(), or add them to the page.
  • "If instanceof is true, the upgrade worked." No. A constructor that throws after super() leaves an element that is an instance of your class, but not upgraded. Check :defined.
  • "A failed upgrade is tried again when you add the element again." No. It fails for good. The browser never runs its constructor again.
  • "When whenDefined() fulfills, every element with that name is upgraded." No. Only the ones in the page. An element off the page still waits.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upWhich label upgrades second?

The page has a label, a box with a label inside it, and a label in the box's shadow root. Which label prints second?

<tea-label>Oolong</tea-label><div id="box">  <tea-label>Black</tea-label></div> <script>  const box = document.querySelector("#box");  box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label> <slot></slot>";  class TeaLabel extends HTMLElement {    connectedCallback() {      console.log(this.textContent);    }  }  customElements.define("tea-label", TeaLabel);</script>
ResultLoading…

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

    Exercise 2 · Warm-upThe name of a subclass

    What does line 5 print?

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

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

      Exercise 3 · PracticeUpgrade it before it joins the page

      Line 8 prints the price's text before it joins the page. Right now it's empty. Add one line at line 7 so the text is there already. What does the console print then?

      <p id="shelf">Black tea.</p> <script type="module">  const price = document.createElement("tea-price");  price.setAttribute("amount", "5");  await import("./tea-kit/tea-price.js");  // Add one line here.  console.log("Text before it joins the page:", price.textContent);  document.querySelector("#shelf").append(" ", price);</script>
      ResultLoading…

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

        Exercise 4 · PracticeA template row that is ready early

        Line 9 prints Ready before adding: false. Change line 7 so the row is upgraded before it's added. What does the fixed page print?

        <p id="shelf"></p><template id="row"><tea-label name="Oolong" minutes="4"></tea-label></template> <script type="module">  await import("./tea-kit/tea-label.js");  const template = document.querySelector("#row");  const row = template.content.cloneNode(true);  customElements.upgrade(row);  console.log("Ready before adding:", row.firstElementChild.matches(":defined"));  document.querySelector("#shelf").append(row);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeThree cups and one bad constructor

          How many cups match :defined at the end? What does line 16 print?

          <tea-cup>1</tea-cup><tea-cup>2</tea-cup><tea-cup>3</tea-cup> <script>  let made = 0;  class TeaCup extends HTMLElement {    constructor() {      super();      made += 1;      if (made === 2) throw new Error("Cup 2 cracked");    }  }  customElements.define("tea-cup", TeaCup);  document.body.append(document.querySelectorAll("tea-cup")[1]);  console.log(document.querySelectorAll("tea-cup:defined").length);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeWait for an element, not just its name

            Write whenUpgraded(element). It should wait until the element's name is defined, then upgrade the element, even off the page. What does your page print?

            <p id="shelf">Mint tea.</p> <script type="module">  async function whenUpgraded(element) {    // Wait for the element's name, then upgrade it.  }   const price = document.createElement("tea-price");  price.setAttribute("amount", "3");  import("./tea-kit/tea-price.js");  await whenUpgraded(price);  console.log("Price text:", price.textContent);  document.querySelector("#shelf").append(" ", price);</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask two things: is the element in the page, and is it still waiting?

              The element upgrades quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What is a custom element upgrade?

                Choose an answer to see the explanation.

              2. Question 2 of 7In the order example, which label's connectedCallback() prints second?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-label>Oolong</tea-label>
                <div id="box"></div>
                <tea-label>Black</tea-label>
                
                <script>
                  const box = document.querySelector("#box");
                  box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label>";
                  const loose = document.createElement("tea-label");
                
                  class TeaLabel extends HTMLElement {
                    connectedCallback() {
                      console.log("Upgraded", this.textContent);
                    }
                  }
                  customElements.define("tea-label", TeaLabel);
                  console.log("Loose label upgraded:", loose instanceof TeaLabel);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7During one element's upgrade, in what order do these run?

                Choose an answer to see the explanation.

              4. Question 4 of 7A script runs document.createElement("tea-label") before tea-label is defined, and doesn't add it to the page. What does define() do to it later?

                Choose an answer to see the explanation.

              5. Question 5 of 7What does line 10 of the template copy example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <p id="shelf"></p>
                <template id="row"><tea-label name="Green tea" minutes="3"></tea-label></template>
                
                <script type="module">
                  await import("./tea-kit/tea-label.js");
                  const template = document.querySelector("#row");
                
                  const copy = template.content.cloneNode(true);
                  customElements.upgrade(copy);
                  console.log("Copy made with cloneNode():", copy.firstElementChild.matches(":defined"));
                
                  const imported = document.importNode(template.content, true);
                  console.log("Copy made with importNode():", imported.firstElementChild.matches(":defined"));
                  document.querySelector("#shelf").append(imported);
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 7What do customElements.get() and customElements.getName() give back for a name or a class nobody defined?

                Choose an answer to see the explanation.

              7. Question 7 of 7An element's constructor throws during its upgrade. What happens when you add that element to the page again later?

                Choose an answer to see the explanation.

              Key takeaways

              • An upgrade gives an element that is already there its class. It's the same object, so references, listeners, attributes, and children stay.
              • define() upgrades the elements with that name in the document, shadow roots included. It goes one at a time, in page order.
              • Your constructor runs first, on the waiting element. Then attributeChangedCallback() runs for each watched attribute, then connectedCallback() if it's in a document.
              • If the constructor throws, the upgrade fails for good. Check :defined, not instanceof.
              • Elements off the page upgrade when they join it, or with customElements.upgrade(). Template copies and elements from documents with no window upgrade only in the page.
              • whenDefined() fulfills with the class after every element in the page is upgraded. get() and getName() look up names and classes.

              Remember the one-liner.
              An upgrade gives the element that is already there its class: the same object, the constructor first, then the callbacks.

              Sources

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

              Coming next: Properties set before the upgrade. A property set too early hides your setter. Learn the pattern that fixes it.

              CompleteFrontend Clear concepts. Working examples.