completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Your first custom element

Learn how to create a custom element: extend HTMLElement, pick a valid name, register it with customElements.define(), and use it from HTML and JavaScript.

By the end, you can
  • 01
    Write and register a custom elementWrite a class that extends HTMLElement, and join it to a name with customElements.define().
  • 02
    Predict what define() acceptsSay which calls define() takes, which error it throws for the rest, and why names follow their rules.
  • 03
    Make the element in three waysCreate it in HTML, with document.createElement(), and with new, and tell an autonomous element from a customized built-in.

How do you create a custom element?

The owner of Leaf and Kettle has a new idea. Some teas on the menu should wear a small badge, like Organic or New harvest. In stage 1, Ravi only used tags that other people wrote. This time he wants to write the tag himself.

He opens tea-kit/tea-label.js from lesson 1.4. It works. But he copied it, and he can't say what each line does. What does extends HTMLElement give his class? What does customElements.define() check? Can he make a badge from JavaScript too?

To create a custom element, write a class that extends HTMLElement. Then call customElements.define() with a name that has a hyphen, and the class. From then on, the browser builds an object of your class for every tag with that name. It does this for tags in your HTML, and for tags you make in JavaScript.

Here is the smallest custom element there is. Its class is empty:

An empty class, registered as tea-badgePop out in the code editor (opens in a new tab)HTML
<tea-badge>Organic</tea-badge><tea-badge>New harvest</tea-badge> <script>  class TeaBadge extends HTMLElement {}   customElements.define("tea-badge", TeaBadge);   for (const badge of document.querySelectorAll("tea-badge")) {    console.log(badge.constructor.name, badge instanceof HTMLElement);  }</script>
ResultLoading…
  • Lines 1 and 2 use the new tag twice, each with its own words inside.
  • Line 5 is the whole class. It has nothing inside the braces. extends HTMLElement means it starts with everything an HTML element has.
  • Line 7 gives the class a name, tea-badge. Now the browser knows which class builds that tag.
  • Line 9 goes through both badges on the page.
  • Line 10 prints the class each badge was built from, and whether it is an HTML element. It prints TeaBadge true, twice.

The result shows Organic and New harvest. Each badge is a real TeaBadge object now. Yet it is still an HTML element, like a <p> or a <button>.

One class, one name, many elements. A card says class TeaBadge and a tag says tea-badge. Arrows from both lead to define(). An arrow from define() leads to a page with two badges, Organic and New harvest, and each one is a TeaBadge object.class TeaBadgethe classtea-badgethe namedefine()pageOrganica TeaBadge objectNew harvesta TeaBadge object
define() joins one class to one name. Then each <tea-badge> on the page is its own object, built from the same class.
Real-life analogyA class is a cookie cutter

A bakery makes star cookies with one cutter. The cutter hangs on a hook, with a label that says "star". Anyone in the kitchen can ask for stars by that name. Every cookie has the same shape, but each one is its own cookie.

In real life: The cookie cutter
In JavaScript: The class TeaBadge
In real life: The label on its hook
In JavaScript: The name tea-badge
In real life: Hanging it up under the label
In JavaScript: customElements.define("tea-badge", TeaBadge)
In real life: Each cookie
In JavaScript: Each <tea-badge> element, its own object
The main idea

A custom element is a class that extends HTMLElement, registered under a name with a hyphen. After customElements.define(), the browser builds that class for every tag with that name.

You met this shape in lesson 1.1. This lesson opens each piece in turn: the class, the define() call, the name, and the ways to make the element. For classes themselves, see Class basics on the JavaScript path.

What does extends HTMLElement give your class?

Look at line 5 again. The class is empty. Still, each badge has a title, a tag name, and a way to listen for clicks. Where does all that come from?

It comes from extends. A class that extends another one starts with everything the other has. Then it adds its own things on top. Inheritance with extends & super teaches this for any class.

HTMLElement is the class behind every HTML element. A <p> is one. So is a <button>. When TeaBadge extends it, every badge gets what all HTML elements share.

Real-life analogyA new branch of a café chain

Asha opens a new branch of a café chain. Head office hands her a working shop: a counter, a till, and an opening hours sign. She doesn't build any of that. She only adds what is special about her branch, like a tea of the day.

In real life: Head office's standard shop
In JavaScript: HTMLElement
In real life: The new branch
In JavaScript: Your class, TeaBadge
In real life: The counter, the till, the opening hours sign
In JavaScript: title, textContent, addEventListener(), and the rest
In real life: The branch's own special
In JavaScript: A method you write, like describe()

Your class even gets a constructor for free. TeaBadge doesn't write one, so JavaScript adds one that calls HTMLElement's constructor for you. Lesson 3.2 shows when to write your own, and what it may do.

Here is a badge with one method of its own, next to things it never wrote:

One method of its own, and things it got for freePop out in the code editor (opens in a new tab)HTML
<tea-badge title="Grown without chemicals">Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {    describe() {      return `This tea is ${this.textContent.toLowerCase()}.`;    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.querySelector("tea-badge");  console.log(badge.describe());  console.log(badge.title);  console.log(badge.tagName);  console.log(badge.isConnected);</script>
ResultLoading…
  • Line 1 gives the badge a title attribute, the text a browser shows when you hover.
  • Lines 5 to 7 are a method that TeaBadge adds. this is the badge itself, so this.textContent is its text.
  • Line 12 calls that method. It prints This tea is organic.
  • Line 13 prints Grown without chemicals. TeaBadge never mentions title.
  • Line 14 prints TEA-BADGE, the tag's name. In an HTML page, tagName is in capitals.
  • Line 15 prints true. isConnected says whether the badge is on the page.

So where do title, tagName, and isConnected live? Not all in one place. HTMLElement extends a class too, and that class extends another. Together they make a chain. When you read a name on the badge, the browser looks in TeaBadge first. If it isn't there, it tries the next class down, and so on.

The chain behind a tea badge. TeaBadge extends HTMLElement extends Element extends Node extends EventTarget. Beside each class, what it gives: describe() from TeaBadge; title, hidden, click() from HTMLElement; tagName, getAttribute() from Element; isConnected, textContent from Node; addEventListener() from EventTarget.TeaBadgedescribe()HTMLElementtitle, hidden, click()ElementtagName, getAttribute()NodeisConnected, textContentEventTargetaddEventListener()
Each arrow means extends. To find a name like title, the browser looks in TeaBadge first, then one link down at a time.

Each link adds its own things:

  • HTMLElement gives what only HTML elements have, like title, hidden, and click().
  • Element gives what every element has, in SVG too, like tagName and getAttribute().
  • Node gives what every piece of the page has, like textContent and isConnected.
  • EventTarget gives addEventListener(), so the badge can listen for events.

Pick a name below. The page climbs the chain itself and prints the class that has it. It uses Object.getPrototypeOf(), which steps one link down. The prototype chain explains how it works.

Playground: where does it come from?
Find the class that gives a badge its namePop out in the code editor (opens in a new tab)HTML
<tea-badge title="Grown without chemicals">Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {    describe() {      return `This tea is ${this.textContent.toLowerCase()}.`;    }  }  customElements.define("tea-badge", TeaBadge);   let link = document.querySelector("tea-badge");  while (!Object.hasOwn(link, "title")) {    link = Object.getPrototypeOf(link);  }  console.log(link.constructor.name);</script>
ResultLoading…
Try it yourself
Line 15 prints HTMLElement

title comes from HTMLElement, with hidden, click(), and style. Every HTML element has them, so your badge does too.

Only the name on line 12 changes. Lines 11 to 14 start at the badge and step down the chain until a class has that name. Each choice runs in a fresh page.

This is also why instanceof works on your badge. badge instanceof HTMLElement is true, because HTMLElement is in its chain. See Extending built-ins & instanceof. Why it matters: you never rebuild what an element already does. You write only what is new about yours.

What does customElements.define() do?

customElements is the page's registry. It is the browser's list of custom tag names, each with its class. Every page has one, and you reach it as window.customElements or just customElements. customElements.get("tea-badge") gives back the class for a name, as lesson 1.1 showed.

define() adds one line to that list. Before it writes anything, it runs four checks, always in the same order:

  1. Is it a class? The second argument must be something you can call with new. If not, it throws a TypeError.
  2. Is the name valid? If not, it throws a SyntaxError. The next section covers the rules.
  3. Is the name free? If this registry already has that name, it throws a NotSupportedError.
  4. Is the class free? If the class already has another name, it throws a NotSupportedError too.

The HTML Standard adds a few more checks for rarer cases, such as the extends option you'll see at the end of this lesson. These four are the ones every definition goes through.

What define() checks, in order. 1. a class? If not, TypeError. 2. a valid name? If not, SyntaxError. 3. name free? If not, NotSupportedError. 4. class free? If not, NotSupportedError. If all four pass, the class is saved in the registry, and tags already on the page are upgraded.1. a class?noTypeError2. a valid name?noSyntaxError3. name free?noNotSupportedError4. class free?noNotSupportedErrorall four passsaved in the registrythen tags on the page upgrade
define() runs four checks, in this order. The first one that fails throws, and the call stops there. If all four pass, the class is saved under its name.

When all four checks pass, it does three more things:

  • It reads your class's special methods, like connectedCallback(), and keeps them. It reads them once, right now.
  • It saves the name and the class together in the registry.
  • It upgrades every tag with that name already on the page. And any whenDefined() promise for the name, from lesson 2.2, resolves.
Real-life analogyThe town hall's book of shop names

To open a shop, you register its name at the town hall. The clerk checks a few things first. Is there a real shop? Is the name written the right way? Does another shop have it? Does your shop already have a name? Only then does the clerk write it in the book.

In real life: The clerk
In JavaScript: customElements.define()
In real life: The book of shop names
In JavaScript: The registry, customElements
In real life: "There's no real shop here"
In JavaScript: A TypeError: not a class
In real life: "That name isn't written the right way"
In JavaScript: A SyntaxError: not a valid name
In real life: "That name is taken" or "you already have a name"
In JavaScript: A NotSupportedError

Try each check. Line 3 always registers tea-badge first. Then line 4 tries a second define():

Playground: what does define() accept?
Two calls to define()Pop out in the code editor (opens in a new tab)JavaScript
class TeaBadge extends HTMLElement {}
class SaleBadge extends HTMLElement {}
customElements.define("tea-badge", TeaBadge);
customElements.define("sale-badge", SaleBadge);
console.log("Both registered");
What Chrome says

Both registered

No error. Both names are in the registry.

Try it yourself
Every check passes

SaleBadge is a class, and sale-badge is a valid name. Neither is in the registry yet. Line 5 prints Both registered.

Line 3 always registers tea-badge first. Line 4 changes, and line 2 too for the arrow function. Press Edit & run to see the message from your own browser.

Every error stops define() at that check. Nothing is saved, and line 5 never runs. The two NotSupportedErrors keep the registry simple: one name for each class, and one class for each name.

The order matters when a call has two problems. define() reports only the first check that fails. Exercise 2 asks you to predict one.

Where should the define() call go? MDN's advice is to register a class right after you write it. That's why each file in the tea kit ends with its own define() line. Loading the file is enough to register the tag.

Notice what isn't on the list. define() never checks that your class extends HTMLElement. That check comes later, when the browser builds an element. The section on autonomous elements shows what happens then.

What makes a valid custom element name?

Lesson 1.1 listed the rules and gave you a name checker. Each rule is there for a reason, and the HTML standard says which. Read each row across: the rule, a name that breaks it, and why the rule exists.

The rules, and why each one exists
The ruleA name that breaks itWhy the rule exists
Start with a lowercase letter, a to z.2-teaThe HTML parser only reads < followed by a letter as a tag. <2-tea> would show up as text.
Have at least one hyphen.teabadgeHTML, SVG, and MathML will never add a tag with a hyphen. So your name can't clash with theirs, now or later.
Have no capital letters, A to Z.tea-BadgeHTML ignores case in tag names. The parser turns <TEA-BADGE> into tea-badge, so only a lowercase name can match.
Have no spaces, no /, and no >.tea-big cupThese end a tag's name in HTML. A name without them is one that document.createElement() can make.
Not be one of the eight reserved names.font-faceSVG and MathML already use these names for tags of their own.

The eight reserved names are the tags in SVG and MathML that already have a hyphen: annotation-xml, color-profile, missing-glyph, and five names that start with font-face.

The capital letters rule surprises people. You can write capitals in your HTML. You just can't give them to define():

Capitals in HTML are finePop out in the code editor (opens in a new tab)HTML
<TEA-BADGE>Organic</TEA-BADGE> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);   const badge = document.querySelector("tea-badge");  console.log(badge.localName, badge instanceof TeaBadge);  console.log(document.createElement("Tea-Badge").localName);</script>
ResultLoading…
  • Line 1 writes the tag in capitals: <TEA-BADGE>.
  • Line 5 registers the name in lowercase, as it must be.
  • Line 8 prints tea-badge true. The browser read the tag as tea-badge, so the class built it.
  • Line 9 prints tea-badge. document.createElement() also turns the name into lowercase.

HTML doesn't care about case in tag names. It turns them into lowercase as it reads. So a lowercase name is the only kind that can ever match.

Newer characters, and Safari

After the first letter, the rules used to allow only a fixed list of characters. In 2025, the HTML standard widened the list to match what the HTML parser already reads. Now almost anything goes after the first letter, except capitals, spaces, /, and >. Chrome 143 and Firefox 149 follow the new rule. So customElements.define("tea-☕", TeaCup) works there.

Safari still uses the older list, which has no ☕. There, the same call throws a SyntaxError. So stick to lowercase letters, digits, and hyphens. Those names work in every browser.

Where does this name work?
  • tea-badge
  • tea-badge-2
  • math-α
  • tea-☕
  • tea-cup!
  • Tea-Badge
  • teabadge
  • 2-tea
  • font-face
Try it yourself
0 of 9 correct

Sort each name by the browsers that accept it in customElements.define().

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

Pick a prefix for your names

A page has one registry, and each name can be in it once. So what if two libraries on one page both want my-button? The second define() throws a NotSupportedError. Every <my-button> then gets the first library's class.

Real-life analogyName labels in a shared fridge

An office has one fridge for everyone. If two people label their boxes "lunch", someone eats the wrong food. So everyone writes their own name first: "Ravi's lunch", "Asha's lunch".

In real life: The office fridge
In JavaScript: The page's one registry
In real life: Two boxes both labelled "lunch"
In JavaScript: Two libraries that both define my-button
In real life: "Ravi's lunch"
In JavaScript: A prefix, like tea-badge

That's why every tag in the tea kit starts with tea-. Real sites do the same. MDN's tags all start with mdn-, as you found in lesson 1.1's last exercise. A prefix can't rule out a clash, but it makes one unlikely. Stage 3 shows a full fix: a scoped registry, a second list of names for one part of the page.

Creating the element from HTML and JavaScript

There are three ways to make a badge. You can write the tag in HTML. You can ask for it by name with document.createElement(). Or you can call the class with new.

In HTML

The browser reads your HTML from top to bottom. A tag can come before its class is registered, or after it:

One badge before define(), one afterPop out in the code editor (opens in a new tab)HTML
<tea-badge>Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);</script> <tea-badge>New harvest</tea-badge> <script>  const [first, second] = document.querySelectorAll("tea-badge");  console.log(first instanceof TeaBadge, second instanceof TeaBadge);</script>
ResultLoading…
  • Line 1 comes before the class. The browser keeps it as a plain element and waits.
  • Line 5 registers the class. It upgrades the badge from line 1, as in lesson 1.1.
  • Line 8 comes after. The browser already knows the name when it reads this tag, so it builds a TeaBadge right away.
  • Line 12 prints true true. Both roads end in the same place.

From JavaScript

document.createElement() makes an element from a tag name. You may know it from Creating & changing elements. It works for your tags too. And because your tag has a class, you can also call that class yourself:

Two badges made from JavaScriptPop out in the code editor (opens in a new tab)HTML
<p>Green tea</p> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);   const organic = document.createElement("tea-badge");  organic.textContent = "Organic";   const fresh = new TeaBadge();  fresh.textContent = "New harvest";   document.querySelector("p").append(" ", organic, " ", fresh);  console.log(organic instanceof TeaBadge, fresh instanceof TeaBadge);</script>
ResultLoading…
  • Line 5 registers the class first.
  • Line 7 asks for a badge by name. Line 8 gives it its text.
  • Line 10 calls the class with new. Line 11 gives that badge its text.
  • Line 13 adds both to the paragraph. Until then, they exist only in JavaScript, off the page.
  • Line 14 prints true true.

The result shows Green tea Organic New harvest. The two badges are the same kind of object. One was asked for by name, the other by class.

Three ways to make a badge. The tag <tea-badge> in HTML and createElement() both arrive at the name tea-badge in the registry. new TeaBadge() arrives at the class TeaBadge. The registry joins the name and the class, and each way gives back a TeaBadge object.<tea-badge>in HTMLcreateElement()by namenew TeaBadge()by classregistrytea-badgeTeaBadgea TeaBadge
HTML and createElement() start from the name. new starts from the class. All three meet in the registry and give back a TeaBadge.

The picture shows the difference. HTML and createElement() start from the name, then look up the class. new starts from the class, then looks up the name. Both lookups go through the registry.

That has a cost. What if the class isn't registered yet? Choose a way below. In both, line 11 registers the class only after line 6 makes the badge:

Playground: make it before define() runs
A badge made before its class is registeredPop out in the code editor (opens in a new tab)HTML
<p>Green tea</p> <script>  class TeaBadge extends HTMLElement {}   const badge = document.createElement("tea-badge");  badge.textContent = "Organic";  document.querySelector("p").append(" ", badge);  console.log(badge instanceof TeaBadge);   customElements.define("tea-badge", TeaBadge);  console.log(badge instanceof TeaBadge);</script>
ResultLoading…
Try it yourself
The page shows "Green tea Organic", and the console prints false, then true

createElement() doesn't need the class yet. Line 6 makes a plain, waiting element, so line 9 prints false. Line 11 registers the class and upgrades the badge, which is already on the page. Line 12 prints true.

Only line 6 changes. The class is registered on line 11, after the badge is made. Each choice runs in a fresh page.

The two ways behave differently. createElement() makes a plain, waiting element when it doesn't know the name yet. Once that element is on the page, define() upgrades it. new TeaBadge() can't wait. Its constructor looks up the class in the registry, to find its name. There is none yet, so Chrome throws TypeError: Failed to construct 'HTMLElement': Illegal constructor. In plain words: this class isn't a registered element yet.

Why it matters: each way has its place.

  • Write the tag in HTML for content that is part of the page, like the menu.
  • Use createElement() when code builds elements from data, or when it might run before the class is registered.
  • Use new when you already have the class, like right after you import it.

What is an autonomous custom element?

Every element in this lesson is an autonomous custom element. "Autonomous" means it stands on its own. It has a tag of its own, like <tea-badge>. Its class extends HTMLElement, and it builds all its behavior itself.

The other kind is a customized built-in element. It keeps a tag HTML already has, like <button>, and adds your class through the is attribute. You saw one in lesson 1.2: a waiter who gets an extra badge, while the café next door ignores it.

So can an autonomous element extend a button's class, to get a button's behavior? Try it. Only line 4 changes:

Playground: which class does it extend?
One badge, three base classesPop out in the code editor (opens in a new tab)HTML
<tea-badge>Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);  console.log("define() worked");   const badge = document.querySelector("tea-badge");  console.log(badge instanceof TeaBadge);</script>
ResultLoading…
Try it yourself
define() works, and so does the badge

An autonomous element extends HTMLElement. The browser builds the badge from your class, so line 9 prints true.

Only line 4 changes. Line 6 prints once define() returns, and line 9 says whether the badge became a TeaBadge. Each choice runs in a fresh page.

In all three, define() works, and line 6 prints. The problem shows up one step later, when the browser builds the badge. A new tag's class must extend HTMLElement, or a class that does, like TeaBadge. It can't go through a built-in element's class, like HTMLButtonElement. Chrome says it plainly: autonomous custom elements must extend HTMLElement. A class that extends nothing fails too, because it can't make an element at all.

When the element can't be built, the tag stays a plain element for good and never matches :defined, as lesson 2.4 showed. Here is how the two kinds compare. Read each row across:

Two kinds of custom element
What you compareAn autonomous elementA customized built-in
What its class extendsHTMLElement, the class every HTML element shares.One built-in element's class, like HTMLButtonElement.
How you register itcustomElements.define("tea-badge", TeaBadge).customElements.define("order-button", OrderButton, { extends: "button" }).
How you write it in HTMLA tag of its own: <tea-badge>.The built-in tag with is: <button is="order-button">.
Which browsers run itChrome, Firefox, and Safari.Chrome and Firefox. Safari doesn't, and WebKit has said it won't.

This course builds autonomous elements, because they work everywhere. Want button behavior? Put a real <button> inside your tag. Lesson 5.7 covers customized built-ins in full.

Building the tea kit's first components

Back to Ravi's kit. In lesson 1.4 he copied first drafts into tea-kit/. Now he rebuilds them with what this lesson showed. Here is the kit's demo page. The kit's files are in the tabs:

The tea kit's demo page and its filesPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  {    "imports": {      "tea-kit": "./tea-kit/index.js",      "tea-kit/": "./tea-kit/"    }  }</script> <p>  <tea-label name="Green tea" minutes="3"></tea-label>  <tea-price amount="4"></tea-price>  <tea-badge>Organic</tea-badge></p> <script type="module">  import "tea-kit";  import { TeaBadge } from "tea-kit/tea-badge.js";   const badge = new TeaBadge();  badge.textContent = "New harvest";  document.querySelector("p").append(" ", badge);  console.log(customElements.get("tea-badge") === TeaBadge);</script>
ResultLoading…
  • Lines 1 to 8 are the import map from lesson 1.4. Line 4 names the whole kit, and line 5 names its folder.
  • Lines 11 to 13 use the three tags in HTML.
  • Line 17 loads the whole kit. Line 18 imports one class from one file, TeaBadge.
  • Lines 20 to 22 make a second badge with new and add it to the page.
  • Line 23 prints true. The class you imported is the one in the registry.

The result shows Green tea: brew for 3 minutes Price: 4 Organic New harvest. Now open the tea-kit/tea-badge.js tab. It's the empty badge from this lesson, with one change: export on line 1. Each kit file now follows the same pattern:

  • One tag per file, named after its tag, with the tea- prefix.
  • A class that extends HTMLElement, so each tag is an autonomous element that works in every browser.
  • export before the class, so a page can import it and call new, as lines 18 and 20 do.
  • customElements.define() at the end of the file, so loading the file registers the tag.

tea-label.js and tea-price.js keep their connectedCallback() from lesson 1.1. The next lessons explain that method and its rules. Because of export, the files are modules. Load them with type="module" or an import, as lesson 1.4 does. The card from lesson 1.4 needs shadow DOM and slots, so it comes back in stage 3.

Common mix-ups

  • "define() checks that my class extends HTMLElement." No. It only checks that it got a class. The browser finds a wrong base class later, when it builds the element.
  • "I can call new TeaBadge() any time." No. Before define() runs, it throws a TypeError. createElement() is the one that can wait.
  • "One class can build two tags." No. A class gets one name. For a second tag, extend the class and register the new one.
  • "<TEA-BADGE> is a different tag from <tea-badge>." No. HTML turns tag names into lowercase. Only define() insists on lowercase.
  • "Only a to z, digits, and hyphens are ever allowed." No. Even the older rule, which Safari still uses, allows dots, underscores, and letters like α. Chrome and Firefox now take even more, like ☕. Plain names are still the safe choice.
  • "You make a custom element with document.registerElement()." No. That was an early version that only Chrome had, and it's gone. See lesson 1.2.

Practice exercises

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

Exercise 1 · Warm-upThe badge's tag name

What does line 8 print?

<tea-badge>Organic</tea-badge> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);   const badge = document.querySelector("tea-badge");  console.log(badge.tagName);</script>
ResultLoading…

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

    Exercise 2 · Warm-upTwo problems in one call

    Line 3 has two problems. Which kind of error does it throw?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const SaleBadge = () => {};
    
    customElements.define("SaleBadge", SaleBadge);

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

      Exercise 3 · PracticeA teapot made with new

      Follow the steps in the comments. What does your last line print?

      <p>Our teapots:</p> <script>  // 1. Write a TeaPot class that extends HTMLElement.  // 2. Register it as tea-pot.  // 3. Make one with new, give it the text "Holds 4 cups", and add it to the p.  // 4. Print whether it's a TeaPot.</script>
      ResultLoading…

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

        Exercise 4 · PracticeFind the bug in the note

        The note never becomes a TeaNote, and the result shows an error. Which kind of error is it, and how do you fix it?

        <tea-note>Steep for 3 minutes</tea-note> <script>  class TeaNote extends HTMLParagraphElement {}  customElements.define("tea-note", TeaNote);   const note = document.querySelector("tea-note");  console.log(note instanceof TeaNote);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeA callback that comes too late

          Line 11 adds a badge to the page. What does the console print?

          <p>Green tea</p> <script>  class TeaBadge extends HTMLElement {}  customElements.define("tea-badge", TeaBadge);   TeaBadge.prototype.connectedCallback = function () {    console.log("Badge connected");  };   document.querySelector("p").append(document.createElement("tea-badge"));  console.log("Done");</script>
          ResultLoading…

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

            Exercise 6 · ChallengeA second tag with the same behavior

            Ravi wants <tea-tag> to work just like <tea-badge>, without copying the class. Fix the page. What does the last line print once it works?

            <tea-badge>Organic</tea-badge><tea-tag>Organic</tea-tag> <script>  class TeaBadge extends HTMLElement {    describe() {      return `This tea is ${this.textContent.toLowerCase()}.`;    }  }  customElements.define("tea-badge", TeaBadge);  customElements.define("tea-tag", TeaBadge);   console.log(document.querySelector("tea-tag").describe());</script>
            ResultLoading…

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

              Check your understanding

              For each question, think about the class, the registry, and the order things happen in.

              The first custom element quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Which call to customElements.define() throws a NotSupportedError?

                Choose an answer to see the explanation.

              2. Question 2 of 7What happens on line 4 of this page?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <script>
                  class TeaBadge extends HTMLElement {}
                
                  const badge = new TeaBadge();
                  customElements.define("tea-badge", TeaBadge);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7In the before-define playground, why does line 12 print true when the badge comes from createElement()?

                Choose an answer to see the explanation.

              4. Question 4 of 7Which name works in every browser?

                Choose an answer to see the explanation.

              5. Question 5 of 7What makes a custom element autonomous?

                Choose an answer to see the explanation.

              6. Question 6 of 7customElements.define("tea-badge", class TeaBadge {}) runs with no error. What happens to the <tea-badge> already on the page?

                Choose an answer to see the explanation.

              7. Question 7 of 7Your badge has a title property, though TeaBadge never mentions it. Where does it come from?

                Choose an answer to see the explanation.

              Key takeaways

              • A custom element is a class that extends HTMLElement, registered with customElements.define().
              • extends HTMLElement gives your class a whole chain: HTMLElement, Element, Node, and EventTarget. You only write what's new.
              • define() checks four things in order: a class, a valid name, a free name, and a free class. Then it saves them and upgrades the page.
              • Each name rule has a reason. Plain lowercase names with a hyphen and a prefix work in every browser.
              • HTML and createElement() start from the name. new starts from the class, so it needs the definition first.
              • Autonomous elements have their own tag and extend HTMLElement. They work everywhere, unlike customized built-ins.

              Remember the one-liner.
              Write a class that extends HTMLElement, give it a name with a hyphen, and the browser builds it for every tag with that name.

              Sources

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

              Coming next: What the constructor may do. Your class can have a constructor, and it runs very early. Learn what belongs there and what must wait.

              CompleteFrontend Clear concepts. Working examples.