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.
- 01Follow the constructor rulesCall
super()first, and keep the constructor to setup that needs nothing from the page. - 02Tell created from upgraded elementsPredict what the constructor sees in each of the five ways an element gets made.
- 03Say 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:
<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>- 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 ofHTMLElement. 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.
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
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
returnanything, except a plainreturnorreturn this. - Don't call
document.write()ordocument.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.
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 runsHTMLElement'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
thisbeforesuper()
Here is what happens when the constructor touches this too early:
class TeaBadge extends HTMLElement {
constructor() {
this.taps = 0;
super();
}
}
customElements.define("tea-badge", TeaBadge);
new TeaBadge();- Line 3 sets
this.tapsbeforesuper()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 reportsTypeError: 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 reportsInvalidStateError: 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. YoursetAttribute()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.
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:
<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>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.
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.
createElement() and the parser check the new badge. One attribute or child fails the check. new and upgrades skip it.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:
<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>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.
Look at the five results together:
- HTML after
define()andcreateElement()run the check, so the badge fails. newruns no check. Nothing looks wrong, so testing withnewhides 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:
<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>- Line 7 adds a class to the new badge.
- Line 12 makes a badge by name. The check finds the
classattribute. - Line 13 prints
false. It's not aTeaBadge.
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:
<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>- 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. Thecatchon 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().
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.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
errorevent
Now try the five ways with a constructor that throws:
<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>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.
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:
| How the badge is made | What the constructor sees | If it adds a child | If 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. |
innerHTML | Its 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:
<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>- Line 6 calls
super()first. - Line 7 gives
tapsa 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:
<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>- 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 inconnectedCallback()and remove them indisconnectedCallback().
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:
super()this.taps = 0this.addEventListener("click", …)this.attachShadow({ mode: "open" })this.getAttribute("label")this.innerHTML = "<b>Tea</b>"this.classList.add("badge")window.addEventListener("resize", …)fetch("/teas.json")
Sort each line by where it belongs in a custom element.
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:
<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>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.
- 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(), astea-labelandtea-pricedo. - 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 afterdefine(), it givesnull. - "The constructor runs when the element is added to the page." No. It runs when the element is made or upgraded.
createElement()andnewrun it off the page. Joining the page isconnectedCallback(). - "If
createElement()fails, atry...catcharound it catches the error." No. It reports the error to the window and hands back a plain, failed element. Onlynewthrows to your code. - "Setting
this.classListorthis.stylein the constructor is harmless." No. Both write attributes, socreateElement()reports aNotSupportedError. - "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.
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><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>label: null. Line 12 runs the constructor on a brand new, empty badge. Line 13 adds the label after it has finished.
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><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>label: Organic, children: 1. innerHTML builds the badge first, label and text included, then upgrades it. So the constructor sees both.
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><p>Teas:</p> <script> class TeaBadge extends HTMLElement { connectedCallback() { if (!this.hasAttribute("tabindex")) { 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>A NotSupportedError: the result must not have attributes. In connectedCallback(), the badge is already on the page, so it can take an attribute. The hasAttribute() check keeps a tabindex the page chose, as web.dev advises. Line 16 prints 0.
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><tea-cup>Green tea</tea-cup> <script> class TeaCup extends HTMLElement { constructor() { super(); this.cups = 1; this.addEventListener("click", () => { this.cups += 1; console.log(`Cups: ${this.cups}`); }); } } customElements.define("tea-cup", TeaCup);</script>Cups: 3. The constructor sets the starting value and the listener, which need nothing from the page. The first click prints Cups: 2, the second Cups: 3.
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><p>Teas:</p> <script> class TeaBadge extends HTMLElement { connectedCallback() { 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>Teas: Organic, with Organic in bold. connectedCallback() runs when line 14 adds the badge. By then, line 13 has set the label, and the badge may take children.
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><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>Reported: 2. Line 15 upgrades the badge from line 1, and line 17 makes one by name. The browser reports both errors. Line 19's error is thrown to the catch, which prints Caught one.
Check your understanding
For each question, ask how the badge was made, and who called its constructor.
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.
Question 2 of 7What does line 11 of this page print?
Read the code, then predict<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.
Question 3 of 7Why must
super()be the first line of the constructor?Choose an answer to see the explanation.
Question 4 of 7Which line belongs in a custom element's constructor?
Choose an answer to see the explanation.
Question 5 of 7A badge's constructor throws while
customElements.define()upgrades it. What happens?Choose an answer to see the explanation.
Question 6 of 7The script comes first on this page, yet line 5 prints
label: Organic. Why?Read the code, then predict<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.
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. Touchingthisbefore it throws aReferenceError. - HTML after
define(),createElement(), andnewmake a new, empty element. HTML beforedefine()andinnerHTMLupgrade one that already has its attributes and children. - A constructor that adds attributes or children makes
createElement()and the parser report aNotSupportedErrorand use a plain, failed element. - Only
newthrows 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:
- HTML Standard: Requirements for custom element constructors and reactions, WHATWG.
- Using custom elements, MDN.
- super, MDN.
- HTML Standard: HTML element constructors, WHATWG.
- HTML Standard: Upgrades, WHATWG.
- HTML Standard: Create an element for a token, WHATWG.
- DOM Standard: Create an element, WHATWG.
- html_construction_site.cc, where Chrome's parser creates an element (158.0.8127.18), Chromium.
- Modern Web Guidance: Custom elements, Chrome for Developers.
- Catching errors thrown from connectedCallback, Nolan Lawson.
- Custom element best practices, web.dev.
- Element: attachShadow() method, MDN.
- Lifecycle, Lit.
- Web component gotcha: constructor vs connectedCallback, Nolan Lawson.
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.