completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

What the constructor may do

Learn the custom element constructor rules: call super() first, don't read or add attributes or children, and see in live examples what breaks if you do.

By the end, you can
  • 01
    Follow the constructor rulesCall super() first, and keep the constructor to setup that needs nothing from the page.
  • 02
    Tell created from upgraded elementsPredict what the constructor sees in each of the five ways an element gets made.
  • 03
    Say what breaks, and where errors goExplain what happens when a constructor adds children or attributes, or throws, and move that work to connectedCallback().

What can a custom element constructor do?

The owner of Leaf and Kettle likes the badges from lesson 3.1. Now Ravi wants each badge to show its label in bold, read from an attribute: <tea-badge label="Organic">. He copies the way an older video does it. The class gets a constructor, the function that runs each time a badge is made. It reads the attribute and fills the badge with innerHTML.

On his menu page, it works. Then Asha tries the badge in her online shop, which builds badges with document.createElement(). Her console says NotSupportedError: Failed to execute 'createElement' on 'Document': The result must not have children, and the badge is empty. One class, two pages. Why does only one of them work?

A custom element's constructor runs the moment the element is made, or upgraded. At that moment, the element is often empty: no attributes and no children. So the constructor calls super() and sets up only what needs nothing from the page. Reading attributes and adding content wait until the element joins the page. Then the browser calls its connectedCallback() method.

Here is one constructor, used two ways:

One constructor, two badgesPop out in the code editor (opens in a new tab)HTML
<tea-badge label="Organic">Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      console.log("label:", this.getAttribute("label"));    }  }  customElements.define("tea-badge", TeaBadge);   const fresh = document.createElement("tea-badge");  fresh.setAttribute("label", "New harvest");</script>
ResultLoading…
  • Line 1 puts a badge in the HTML, with a label. No class exists yet when the browser reads it.
  • Line 5 starts the class's own constructor. It runs once for each badge.
  • Line 6 calls super(), the constructor of HTMLElement. The next section shows why it comes first.
  • Line 7 prints the label the constructor can see.
  • Line 10 registers the class. The browser upgrades the badge from line 1, and its constructor prints label: Organic.
  • Line 12 makes a second badge by name. Its constructor runs at once and prints label: null.
  • Line 13 gives that badge its label. By then, its constructor has finished.

The same line printed two different things. The first badge was upgraded: it already had its label when its constructor ran. The second badge was made new, and it was still empty. That is Ravi's whole problem. His menu page upgrades its badges. Asha's shop makes new ones.

When the constructor runs. A badge made new: first the constructor, then its label is added, then its text, so the constructor sees nothing yet. An upgraded badge: it already has its label and text, then the constructor runs and sees both.made newconstructor()+ label+ textsees nothing yetupgradedlabel + textconstructor()sees label and text
A new badge meets its constructor empty. Its label and text come after. An upgraded badge already has both when its constructor runs.
Real-life analogyA potter makes an empty teapot

A potter shapes a teapot on her wheel. She doesn't pour tea into it there. The pot isn't on a table yet, and nobody has said which tea they want. It gets filled later, at the table, once someone orders.

In real life: Shaping the pot on the wheel
In JavaScript: The constructor
In real life: The new, empty teapot
In JavaScript: A new element, with no attributes or children
In real life: Filling it at the table, once someone orders
In JavaScript: connectedCallback(), when the element joins the page
In real life: Pouring tea in at the wheel
In JavaScript: Adding children in the constructor
The main idea

A custom element's constructor runs as soon as the element is made or upgraded, often before it has attributes or children. Call super() first. Set up the element itself, and leave reading or adding attributes and children for later.

The HTML Standard lists the rules in a short section, Requirements for custom element constructors. In plain words:

  • Call super() first, with no arguments.
  • Don't return anything, except a plain return or return this.
  • Don't call document.write() or document.open().
  • Don't read the element's attributes or children.
  • Don't give the element attributes or children.
  • Leave most work, like fetching data or drawing content, for connectedCallback().

MDN's guide agrees. The constructor sets up the starting state, default values, event listeners, and maybe a shadow root. The sections below test each rule in Chrome, in every way an element can be made.

Why must super() come first?

In lesson 3.1, TeaBadge had no constructor. JavaScript gave it one for free, and that one just calls super(). Once you write your own constructor, calling super() is your job.

super() runs the constructor of the class you extend, here HTMLElement. That constructor is what hands your class its element. Before it runs, there is no element yet, so this doesn't exist. Inheritance with extends & super explains this for any class.

Real-life analogyThe front desk hands you a key card

Asha checks in at a hotel. Before she can open her room, the front desk has to hand her a key card. If she walks straight to the room, the door stays shut. Once she has the card, she can unpack.

In real life: The front desk
In JavaScript: super(), which runs HTMLElement's constructor
In real life: The key card to your room
In JavaScript: this, the element
In real life: Unpacking in the room
In JavaScript: Setting up the element
In real life: Trying the door before you have a card
In JavaScript: Touching this before super()

Here is what happens when the constructor touches this too early:

this before super() (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
class TeaBadge extends HTMLElement {
  constructor() {
    this.taps = 0;
    super();
  }
}
customElements.define("tea-badge", TeaBadge);

new TeaBadge();
  • Line 3 sets this.taps before super() has run.
  • Line 4 calls super(), one line too late.
  • Line 9 makes a badge with new, which runs the constructor.

Chrome throws ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor. A derived class is one that uses extends. In plain words: call super() before you use this. Swap lines 3 and 4, and it works.

Mistakes Chrome stops with an error

Three more mistakes in the constructor's own code end in an error. Here is what Chrome says:

  • Call super() once. JavaScript throws on a second call: ReferenceError: Super constructor may only be called once.
  • Don't return a different object, like a new <span>. During an upgrade, Chrome reports TypeError: custom element constructors must call super() first and must not return a different object.
  • Don't call document.write(). For a tag the parser is building, Chrome reports InvalidStateError: Failed to execute 'write' on 'Document': Custom Element constructor should not use write().

Notice the words "reports" and "throws". When the browser makes the element from HTML, an error in the constructor isn't thrown to any code of yours. It's reported, and the tag is left as a plain element. The section on errors shows where it goes.

Why it matters: if your element has nothing to set up, leave the constructor out. The free one calls super() for you, and there's nothing to get wrong.

Why does getAttribute() return null in the constructor?

In the first example, the constructor read Organic once and null once. It depends on how the badge was made. There are five ways, and they fall into two groups.

Elements made new

Three ways build a brand new element and run its constructor straight away:

  • HTML, after define(). The parser reads a tag whose class is already registered. It runs the constructor first, then adds the tag's attributes, then reads its children. Chrome's parser code does it in that order.
  • document.createElement(). It runs the constructor before it returns. Your setAttribute() calls come after.
  • new TeaBadge(). The same. Nothing can come before the constructor.

In all three, the constructor sees an empty element.

Upgraded elements

The other two ways make the element first and run the constructor later. That's an upgrade, which you met in lesson 2.4:

  • HTML, before define(). The tag waits, with its attributes and children, until the class is registered.
  • innerHTML. It never runs a constructor while it reads your string. It builds waiting elements, attributes and children included. Then it upgrades them, once it's done.

In both, the constructor sees whatever the element already has.

Five ways to make a badge, in two groups. Made new, so the constructor sees label: null and children: 0: HTML after define(), createElement(), new TeaBadge(). Upgraded, so the constructor sees label: Organic and children: 1: HTML before define(), innerHTML.made newHTML after define()createElement()new TeaBadge()label: nullchildren: 0upgradedHTML before define()innerHTMLlabel: Organicchildren: 1
Three ways make a new badge, so its constructor sees nothing. Two ways upgrade a badge that already has its label and text, so its constructor sees both.

Try all five. The constructor in tea-badge.js, the second tab, prints the label and the number of children it sees. Only the page changes:

Playground: what does the constructor see?
One badge, made five ways, with a constructor that looksPop out in the code editor (opens in a new tab)HTML
<script src="tea-badge.js"></script> <p>Teas: <tea-badge label="Organic">Organic</tea-badge></p> <script>  const badge = document.querySelector("tea-badge");  console.log("Defined:", badge.matches(":defined"));</script>
ResultLoading…
Try it yourself
The constructor prints label: null, children: 0

Line 1 registers the class before the tag is read. So the parser runs the constructor as soon as it reads <tea-badge on line 3. It adds the label and the text after the constructor returns.

Pick how the badge is made. Only the page changes. tea-badge.js, in the second tab, stays the same. Each choice runs in a fresh page.
Real-life analogySetting a table before or after the guests sit

A waiter sets a table for a party. Sometimes the guests are already sitting there, and she can greet each one by name. Other times she gets there first, and the chairs are empty. A note that says "greet the guest in seat 1" only works when the guests came first.

In real life: The waiter setting the table
In JavaScript: The constructor
In real life: Guests already in their seats
In JavaScript: An upgraded element, with its attributes and children
In real life: Empty chairs
In JavaScript: A new element
In real life: "Greet the guest in seat 1"
In JavaScript: this.getAttribute("label")

That's why reading attributes in the constructor is a trap. It doesn't fail every time. It works in the two upgrade ways, and gives null in the other three. The HTML Standard says it plainly: a new element has none, and relying on upgrades makes the element harder to use.

The trap is easy to miss. Pages often load components with <script type="module">, as lesson 1.4 does. Module scripts wait until the whole HTML is read. So every tag in the HTML is upgraded, and the constructor finds its label. Ravi's menu page works. The bug only shows when someone makes a badge from JavaScript, like Asha's shop.

So where should the badge read its label? When it joins the page, in connectedCallback(). Lesson 3.3 covers that method. Lesson 3.4 shows how to react when an attribute changes later.

Can the constructor set innerHTML or add attributes?

Ravi's constructor also filled the badge with innerHTML. That breaks the other half of the rule. The constructor must not give the element attributes or children.

Why? Because of what document.createElement() promises. Code that calls it expects an empty element back, every time. The DOM Standard makes sure of it. Right after the constructor returns, createElement() checks the new element. The parser runs the same check on a tag whose class is registered:

  • Does it have any attributes?
  • Does it have any children?
  • Is it already inside a parent?
  • Does it belong to another document?
  • Does it have a different tag name?

One "yes" is enough. The browser reports a NotSupportedError and puts a plain element in place of yours. That element's state is failed, from lesson 2.4. Its class is HTMLUnknownElement, the class for tags HTML doesn't know.

The check after the constructor. When the constructor is done, the browser asks: any attributes? any children? If yes, a NotSupportedError is reported, and a plain, failed element is used instead. If both are no, you get a TeaBadge.constructor() doneany attributes?yesNotSupportedErrorany children?yesNotSupportedErrorreported, and a plainfailed element is usedboth noa TeaBadge
After the constructor, createElement() and the parser check the new badge. One attribute or child fails the check. new and upgrades skip it.
Real-life analogyAn order for an empty box

Asha orders empty boxes to pack her tea. One day a box arrives with old newspapers inside. The packer meant well, but she can't use it. She sends it back and takes a plain box from the shelf instead.

In real life: The order for an empty box
In JavaScript: document.createElement()
In real life: The packer
In JavaScript: The constructor
In real life: Old newspapers inside
In JavaScript: Attributes or children the constructor added
In real life: Sending the box back
In JavaScript: The NotSupportedError
In real life: A plain box from the shelf
In JavaScript: The failed HTMLUnknownElement

Now try it. In this version of tea-badge.js, line 4 sets innerHTML:

Playground: a constructor that adds a child
One badge, made five ways, with a constructor that sets innerHTMLPop out in the code editor (opens in a new tab)HTML
<script src="tea-badge.js"></script> <p>Teas: <tea-badge label="Organic">Organic</tea-badge></p> <script>  const badge = document.querySelector("tea-badge");  console.log("Defined:", badge.matches(":defined"));</script>
ResultLoading…
Try it yourself
Chrome reports NotSupportedError, and the page prints Defined: false

The parser checks the new badge, finds the child, and reports a NotSupportedError. A plain, failed element takes the badge's place on line 3. Line 7 prints Defined: false.

Pick how the badge is made. Only the page changes. tea-badge.js, in the second tab, stays the same. Each choice runs in a fresh page.

Look at the five results together:

  • HTML after define() and createElement() run the check, so the badge fails.
  • new runs no check. Nothing looks wrong, so testing with new hides the bug.
  • The two upgrades run no check either. But the constructor wiped out the page's own text, Organic, and wrote Tea.

Some older tutorials and videos set innerHTML in the constructor. When the demo page loads the script after the HTML, every tag is an upgrade, and it seems to work. Now you know why it breaks elsewhere.

Properties that write attributes

Attributes can sneak in through properties too. classList.add() writes the class attribute:

classList in the constructor (an error on purpose)Pop out in the code editor (opens in a new tab)HTML
<p>Teas:</p> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      this.classList.add("badge");    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.createElement("tea-badge");  console.log(badge instanceof TeaBadge);</script>
ResultLoading…
  • Line 7 adds a class to the new badge.
  • Line 12 makes a badge by name. The check finds the class attribute.
  • Line 13 prints false. It's not a TeaBadge.

Chrome reports NotSupportedError: Failed to execute 'createElement' on 'Document': The result must not have attributes. The same happens with this.style.color, this.hidden, this.tabIndex, this.title, and this.dataset. Each one writes an attribute. A property of your own, like this.taps = 0, is fine, because it isn't an attribute.

Why it matters: anyone who builds your element from JavaScript gets a broken one. Do this work in connectedCallback(), once the element is on the page.

What happens when a constructor throws an error?

A constructor can throw an error, by mistake or on purpose. Where does that error go? It depends on who called the constructor.

With new TeaBadge(), your code called it. So the error is thrown back to your code, like any other. A try...catch around new catches it.

In the other four ways, the browser called the constructor. It catches the error itself, then reports it. Reporting means two things. The error goes to the window's error event, and the console prints it as "Uncaught". Your own catch never sees it.

Here, a badge in the HTML is upgraded by define(), and its constructor throws:

An upgrade error skips the try (an error on purpose)Pop out in the code editor (opens in a new tab)HTML
<tea-badge>Organic</tea-badge> <script>  window.addEventListener("error", (event) => {    console.log("Reported:", event.error.message);  });   class TeaBadge extends HTMLElement {    constructor() {      super();      throw new Error("The badge broke");    }  }   try {    customElements.define("tea-badge", TeaBadge);    console.log("define() is done");  } catch (error) {    console.log("Caught:", error.message);  }</script>
ResultLoading…
  • Lines 4 to 6 listen for reported errors on the window.
  • Line 11 throws inside the constructor.
  • Line 16 registers the class, and the browser upgrades the badge from line 1.
  • Line 17 prints define() is done. The catch on line 18 never runs.

The console shows Reported: The badge broke, then define() is done. The error skipped the try and went straight to the window. Nolan Lawson found the same with errors from connectedCallback().

Where a constructor's error goes. With new TeaBadge(), it is thrown to your try and catch. With the other four ways, it is reported to the window's error event, and a failed element is left behind.new TeaBadge()try { } catchthrown to your codethe other four wayserror eventfailed tagreportedleft behind
new throws a constructor's error straight back to your code. In the other four ways, the browser reports it to the window's error event, and leaves a failed element behind.
Real-life analogyBad news by phone or on the notice board

Ravi phones a plumber himself. If the job can't be done, the plumber tells him on the phone, right away. But when the landlord books the plumber, any bad news goes up on the notice board in the hall. Ravi's phone never rings. He only finds out if he reads the board.

In real life: Ravi phoning the plumber himself
In JavaScript: new TeaBadge()
In real life: Bad news on the phone
In JavaScript: The error, thrown to your try...catch
In real life: The landlord booking the plumber
In JavaScript: The browser making the element
In real life: The notice board in the hall
In JavaScript: The window's error event

Now try the five ways with a constructor that throws:

Playground: a constructor that throws
One badge, made five ways, with a constructor that throwsPop out in the code editor (opens in a new tab)HTML
<script src="tea-badge.js"></script> <p>Teas: <tea-badge label="Organic">Organic</tea-badge></p> <script>  const badge = document.querySelector("tea-badge");  console.log("Defined:", badge.matches(":defined"));</script>
ResultLoading…
Try it yourself
Chrome reports Error, and the page prints Defined: false

The parser catches the error and reports it. A plain, failed element takes the badge's place, and the page goes on. Line 7 prints Defined: false.

Pick how the badge is made. Only the page changes. tea-badge.js, in the second tab, stays the same. Each choice runs in a fresh page.

What's left behind? In the four reported ways, the badge is broken for good. It never matches :defined, as lesson 2.4 showed. Its callbacks never run. The browser never tries its constructor again, even if you move it. customElements.get() still returns the class, and whenDefined() still resolves. Only this one element is broken.

Here are the five ways side by side. Read each row across:

The five ways side by side
How the badge is madeWhat the constructor seesIf it adds a childIf it throws
A tag in the HTML, read after define().No attributes and no children yet.A NotSupportedError is reported. A plain, failed element takes its place.The error is reported. A plain, failed element takes its place.
document.createElement("tea-badge")No attributes and no children.A NotSupportedError is reported. You get back a plain, failed element.The error is reported. You get back a plain, failed element.
new TeaBadge()No attributes and no children.No error. The badge keeps its child.The error is thrown to your code.
A tag in the HTML, read before define().Its attributes and children.No error. The child replaces what the page wrote.The error is reported. The tag stays failed.
innerHTMLIts attributes and children, because it's upgraded.No error. The child replaces what the page wrote.The error is reported. The tag stays failed.

What should go in a custom element constructor?

So what may the constructor do? The HTML Standard and MDN give the same short list. Set up the starting state and default values. Add event listeners. Maybe attach a shadow root. Each of these works on the element alone, so it works in every way the element is made.

Here is a badge that counts taps:

A default value and a click listenerPop out in the code editor (opens in a new tab)HTML
<p><tea-badge>Organic</tea-badge></p> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      this.taps = 0;      this.addEventListener("click", () => {        this.taps += 1;        console.log(`${this.textContent} taps: ${this.taps}`);      });    }  }  customElements.define("tea-badge", TeaBadge);   const fresh = document.createElement("tea-badge");  fresh.textContent = "New harvest";  document.querySelector("p").append(" ", fresh);</script>
ResultLoading…
  • Line 6 calls super() first.
  • Line 7 gives taps a starting value of 0. It's a property, not an attribute.
  • Lines 8 to 11 listen for clicks on the badge itself. Each click adds 1 and prints the count.
  • Lines 16 to 18 make a second badge by name. There's no error.

Click Organic twice and New harvest once. The console prints Organic taps: 1, Organic taps: 2, and New harvest taps: 1. The upgraded badge and the new one behave the same. Lit's docs add that a listener on the element itself never needs removing.

A shadow root is not a child

A shadow root is a private tree of elements inside your element, kept apart from the page. Stage 3 builds them. For now, one fact matters. A shadow root doesn't count as a child, so the constructor may attach one and fill it:

A shadow root filled in the constructorPop out in the code editor (opens in a new tab)HTML
<p>Teas:</p> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = "<b>Organic</b>";    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.createElement("tea-badge");  document.querySelector("p").append(" ", badge);  console.log(badge.childNodes.length);</script>
ResultLoading…
  • Line 7 attaches an open shadow root.
  • Line 8 puts a bold Organic inside it.
  • Line 13 makes the badge by name, and the check passes.
  • Line 15 prints 0. The badge itself has no children.

The badge shows a bold Organic. web.dev's best practices say to create the shadow root in the constructor. A later callback can run many times, so it would have to check for an old shadow root first.

What waits for connectedCallback()

Everything that needs the page waits until the element joins it:

  • Reading attributes and children.
  • Adding attributes and children, like a class or a default tabindex.
  • Fetching data and drawing the element's content, as the HTML Standard asks.
  • Listeners on things outside the element, like window. Lit's docs add them in connectedCallback() and remove them in disconnectedCallback().

The standard adds one warning. connectedCallback() can run more than once, each time the element joins a page. So one-time work there needs a check. Lesson 3.3 shows how.

Nolan Lawson points out the opposite mistake: setup in the constructor, and cleanup in disconnectedCallback(). The constructor runs once, but the element can leave and come back many times. After its first trip, the cleanup has run, and the setup never comes back.

Lit, the library in stage 8, follows the same rules. Its constructor sets default values, and its first render waits until the element is connected. Sort each line into its place:

Constructor or connectedCallback()?
  • super()
  • this.taps = 0
  • this.addEventListener("click", …)
  • this.attachShadow({ mode: "open" })
  • this.getAttribute("label")
  • this.innerHTML = "<b>Tea</b>"
  • this.classList.add("badge")
  • window.addEventListener("resize", …)
  • fetch("/teas.json")
Try it yourself
0 of 9 correct

Sort each line by where it belongs in a custom element.

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

Checking the tea kit against the rules

Ravi checks his tea kit from lesson 3.1. tea-label.js reads its name and minutes. Should it do that in the constructor, like his badge did? He tries both versions on one page, which makes a label three ways. Pick a version:

Playground: where should tea-label read its attributes?
Three tea labels: from the HTML, by name, and with newPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "tea-kit/": "./tea-kit/" } }</script> <p><tea-label name="Green tea" minutes="3"></tea-label></p><p></p><p></p> <script type="module">  import { TeaLabel } from "tea-kit/tea-label.js";   const oolong = document.createElement("tea-label");  oolong.setAttribute("name", "Oolong");  oolong.setAttribute("minutes", "4");  document.querySelectorAll("p")[1].append(oolong);   const black = new TeaLabel();  black.setAttribute("name", "Black tea");  black.setAttribute("minutes", "5");  document.querySelectorAll("p")[2].append(black);   for (const label of document.querySelectorAll("tea-label")) {    console.log(label.textContent || "(empty)");  }</script>
ResultLoading…
Try it yourself
All three labels work

The kit's label reads its attributes in connectedCallback(), which runs when the label joins the page. By then, all three have their name and minutes, however they were made.

The page stays the same. Only tea-kit/tea-label.js changes: open its tab to compare. Each choice runs in a fresh page.
  • Lines 1 to 3 are an import map for the kit's folder, as in lesson 1.4.
  • Line 5 writes a label in the HTML. The module script waits for the HTML, so this label is upgraded.
  • Lines 12 to 15 make a label by name, give it its attributes, and add it to the page.
  • Lines 17 to 20 do the same with new.
  • Lines 22 to 24 print each label's text, or (empty).

With the kit's version, all three labels print. With Ravi's version, only the label from the HTML works. The one from createElement() is empty, and the one from new says null: brew for null minutes.

So the kit stays as it is. Its components already follow the rules:

  • No constructor, unless there's setup that needs nothing from the page.
  • Reading attributes waits for connectedCallback(), as tea-label and tea-price do.
  • Every tag works however it's made: from HTML, by name, or with new.

Ravi fixes his badge the same way, in exercise 5.

Common mix-ups

  • "Reading attributes in the constructor works. I tried it." No. It works only for upgraded elements. With createElement(), new, or a tag read after define(), it gives null.
  • "The constructor runs when the element is added to the page." No. It runs when the element is made or upgraded. createElement() and new run it off the page. Joining the page is connectedCallback().
  • "If createElement() fails, a try...catch around it catches the error." No. It reports the error to the window and hands back a plain, failed element. Only new throws to your code.
  • "Setting this.classList or this.style in the constructor is harmless." No. Both write attributes, so createElement() reports a NotSupportedError.
  • "Wrapping the work in queueMicrotask() makes it safe." No. The browser can run waiting microtasks right after the constructor, before its check. A tag the parser builds still fails. See microtasks.
  • "A shadow root counts as children." No. Attaching and filling a shadow root in the constructor is fine. The badge itself stays empty.
  • "Every custom element needs a constructor." No. Leave it out if there's nothing to set up. JavaScript adds one that calls super().

Practice exercises

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

Exercise 1 · Warm-upWhat new sees

What does line 7 print?

<p>Teas:</p>

<script>
  class TeaBadge extends HTMLElement {
    constructor() {
      super();
      console.log("label:", this.getAttribute("label"));
    }
  }
  customElements.define("tea-badge", TeaBadge);

  const badge = new TeaBadge();
  badge.setAttribute("label", "Fair trade");
  document.querySelector("p").append(" ", badge);
</script>

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

    Exercise 2 · Warm-upWhat innerHTML sees

    What does line 8 print?

    <p></p>
    
    <script>
      class TeaBadge extends HTMLElement {
        constructor() {
          super();
          const label = this.getAttribute("label");
          console.log(`label: ${label}, children: ${this.childNodes.length}`);
        }
      }
      customElements.define("tea-badge", TeaBadge);
    
      const p = document.querySelector("p");
      p.innerHTML = '<tea-badge label="Organic">Organic</tea-badge>';
    </script>

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

      Exercise 3 · PracticeFind the bug in the tab stop

      Ravi wants every badge to be reachable with the Tab key, so line 7 sets tabIndex. The console shows an error, and line 15 prints -1. Which kind of error is it, and how do you fix it?

      <p>Teas:</p> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      this.tabIndex = 0;    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.createElement("tea-badge");  badge.textContent = "Organic";  document.querySelector("p").append(" ", badge);  console.log(badge.tabIndex);</script>
      ResultLoading…

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

        Exercise 4 · PracticeA cup that counts

        Follow the steps in the comments. Then click the cup twice. What does the console print last?

        <tea-cup>Green tea</tea-cup> <script>  // 1. Write a TeaCup class that extends HTMLElement, with a constructor.  // 2. In it, call super(), set this.cups to 1, and listen for clicks.  // 3. On each click, add 1 to this.cups and print "Cups: " and the number.  // 4. Register it as tea-cup.</script>
        ResultLoading…

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

          Exercise 5 · ChallengeFix Ravi's badge

          This is Ravi's badge in Asha's shop. Make it work without changing lines 13 to 15. What does the result show once it works?

          <p>Teas:</p> <script>  class TeaBadge extends HTMLElement {    constructor() {      super();      const label = this.getAttribute("label");      this.innerHTML = `<b>${label}</b>`;    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.createElement("tea-badge");  badge.setAttribute("label", "Organic");  document.querySelector("p").append(" ", badge);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeCount the reported errors

            What does line 23 print?

            <tea-badge>Organic</tea-badge>
            
            <script>
              let reported = 0;
              window.addEventListener("error", () => {
                reported += 1;
              });
            
              class TeaBadge extends HTMLElement {
                constructor() {
                  super();
                  throw new Error("The badge broke");
                }
              }
              customElements.define("tea-badge", TeaBadge);
            
              document.createElement("tea-badge");
              try {
                new TeaBadge();
              } catch {
                console.log("Caught one");
              }
              console.log("Reported:", reported);
            </script>

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

              Check your understanding

              For each question, ask how the badge was made, and who called its constructor.

              The constructor rules quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Which way of making a badge hands the constructor an element that already has its attributes and children?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does line 11 of this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <script>
                  class TeaBadge extends HTMLElement {
                    constructor() {
                      super();
                      this.textContent = "Tea";
                    }
                  }
                  customElements.define("tea-badge", TeaBadge);
                
                  const badge = document.createElement("tea-badge");
                  console.log(badge instanceof TeaBadge);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7Why must super() be the first line of the constructor?

                Choose an answer to see the explanation.

              4. Question 4 of 7Which line belongs in a custom element's constructor?

                Choose an answer to see the explanation.

              5. Question 5 of 7A badge's constructor throws while customElements.define() upgrades it. What happens?

                Choose an answer to see the explanation.

              6. Question 6 of 7The script comes first on this page, yet line 5 prints label: Organic. Why?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <script type="module">
                  class TeaBadge extends HTMLElement {
                    constructor() {
                      super();
                      console.log("label:", this.getAttribute("label"));
                    }
                  }
                  customElements.define("tea-badge", TeaBadge);
                </script>
                
                <tea-badge label="Organic">Organic</tea-badge>

                Choose an answer to see the explanation.

              7. Question 7 of 7A badge's constructor sets this.innerHTML. What makes it work however the badge is made?

                Choose an answer to see the explanation.

              Key takeaways

              • A custom element's constructor runs when the element is made or upgraded, often before it has attributes or children.
              • Call super() first. Touching this before it throws a ReferenceError.
              • HTML after define(), createElement(), and new make a new, empty element. HTML before define() and innerHTML upgrade one that already has its attributes and children.
              • A constructor that adds attributes or children makes createElement() and the parser report a NotSupportedError and use a plain, failed element.
              • Only new throws a constructor's error to your code. The other ways report it to the window, and the element stays failed.
              • The constructor sets default values, listeners on the element, and a shadow root. Everything else waits for connectedCallback().

              Remember the one-liner.
              Shape the empty element in the constructor, and fill it in connectedCallback().

              Sources

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

              Coming next: connectedCallback and disconnectedCallback. Run setup when the element joins the page, and clean up when it leaves, even if that happens many times.

              CompleteFrontend Clear concepts. Working examples.