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.
- 01Write and register a custom elementWrite a class that extends
HTMLElement, and join it to a name withcustomElements.define(). - 02Predict what define() acceptsSay which calls
define()takes, which error it throws for the rest, and why names follow their rules. - 03Make the element in three waysCreate it in HTML, with
document.createElement(), and withnew, 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:
<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>- 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 HTMLElementmeans 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>.
define() joins one class to one name. Then each <tea-badge> on the page is its own object, built from the same class.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
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.
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:
<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>- Line 1 gives the badge a
titleattribute, the text a browser shows when you hover. - Lines 5 to 7 are a method that
TeaBadgeadds.thisis the badge itself, sothis.textContentis its text. - Line 12 calls that method. It prints
This tea is organic. - Line 13 prints
Grown without chemicals.TeaBadgenever mentionstitle. - Line 14 prints
TEA-BADGE, the tag's name. In an HTML page,tagNameis in capitals. - Line 15 prints
true.isConnectedsays 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.
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:
HTMLElementgives what only HTML elements have, liketitle,hidden, andclick().Elementgives what every element has, in SVG too, liketagNameandgetAttribute().Nodegives what every piece of the page has, liketextContentandisConnected.EventTargetgivesaddEventListener(), 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.
<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>title comes from HTMLElement, with hidden, click(), and style. Every HTML element has them, so your badge does too.
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:
- Is it a class? The second argument must be something you can call with
new. If not, it throws aTypeError. - Is the name valid? If not, it throws a
SyntaxError. The next section covers the rules. - Is the name free? If this registry already has that name, it throws a
NotSupportedError. - Is the class free? If the class already has another name, it throws a
NotSupportedErrortoo.
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.
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.
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():
class TeaBadge extends HTMLElement {}
class SaleBadge extends HTMLElement {}
customElements.define("tea-badge", TeaBadge);
customElements.define("sale-badge", SaleBadge);
console.log("Both registered");Both registered
No error. Both names are in the registry.
SaleBadge is a class, and sale-badge is a valid name. Neither is in the registry yet. Line 5 prints Both registered.
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 rule | A name that breaks it | Why the rule exists |
|---|---|---|
| Start with a lowercase letter, a to z. | 2-tea | The HTML parser only reads < followed by a letter as a tag. <2-tea> would show up as text. |
| Have at least one hyphen. | teabadge | HTML, 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-Badge | HTML 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 cup | These 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-face | SVG 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():
<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>- 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 astea-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.
tea-badgetea-badge-2math-αtea-☕tea-cup!Tea-Badgeteabadge2-teafont-face
Sort each name by the browsers that accept it in customElements.define().
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.
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:
<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>- 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
TeaBadgeright 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:
<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>- 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.
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:
<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>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.
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
newwhen 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:
<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>An autonomous element extends HTMLElement. The browser builds the badge from your class, so line 9 prints true.
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:
| What you compare | An autonomous element | A customized built-in |
|---|---|---|
| What its class extends | HTMLElement, the class every HTML element shares. | One built-in element's class, like HTMLButtonElement. |
| How you register it | customElements.define("tea-badge", TeaBadge). | customElements.define("order-button", OrderButton, { extends: "button" }). |
| How you write it in HTML | A tag of its own: <tea-badge>. | The built-in tag with is: <button is="order-button">. |
| Which browsers run it | Chrome, 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:
<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>- 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
newand 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. exportbefore the class, so a page can import it and callnew, 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 extendsHTMLElement." 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. Beforedefine()runs, it throws aTypeError.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. Onlydefine()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.
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>TEA-BADGE. tagName is in capitals in an HTML page. localName would give tea-badge.
Line 3 has two problems. Which kind of error does it throw?
const SaleBadge = () => {};
customElements.define("SaleBadge", SaleBadge);A TypeError. SaleBadge is an arrow function, and check 1 fails before define() looks at the name. Fix that, and you'd get a SyntaxError for SaleBadge next.
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><p>Our teapots:</p> <script> class TeaPot extends HTMLElement {} customElements.define("tea-pot", TeaPot); const pot = new TeaPot(); pot.textContent = "Holds 4 cups"; document.querySelector("p").append(" ", pot); console.log(pot instanceof TeaPot);</script>true. The class is registered before new runs, so it builds a TeaPot. The page shows Our teapots: Holds 4 cups.
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><tea-note>Steep for 3 minutes</tea-note> <script> class TeaNote extends HTMLElement {} customElements.define("tea-note", TeaNote); const note = document.querySelector("tea-note"); console.log(note instanceof TeaNote);</script>A TypeError: autonomous custom elements must extend HTMLElement. <tea-note> is a tag of its own, so line 4 must say extends HTMLElement. Then line 8 prints true.
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><p>Green tea</p> <script> class TeaBadge extends HTMLElement { connectedCallback() { console.log("Badge connected"); } } customElements.define("tea-badge", TeaBadge); document.querySelector("p").append(document.createElement("tea-badge")); console.log("Done");</script>Only Done. define() read the class's callbacks on line 5, and there were none. The method added on line 7 is never seen. Put it inside the class, and the console prints Badge connected, then Done.
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><tea-badge>Organic</tea-badge><tea-tag>Organic</tea-tag> <script> class TeaBadge extends HTMLElement { describe() { return `This tea is ${this.textContent.toLowerCase()}.`; } } class TeaTag extends TeaBadge {} customElements.define("tea-badge", TeaBadge); customElements.define("tea-tag", TeaTag); console.log(document.querySelector("tea-tag").describe());</script>This tea is organic. TeaTag is a new class, so check 4 passes. It extends TeaBadge, so describe() is in its chain.
Check your understanding
For each question, think about the class, the registry, and the order things happen in.
Question 1 of 7Which call to
customElements.define()throws aNotSupportedError?Choose an answer to see the explanation.
Question 2 of 7What happens on line 4 of this page?
Read the code, then predict<script> class TeaBadge extends HTMLElement {} const badge = new TeaBadge(); customElements.define("tea-badge", TeaBadge); </script>Choose an answer to see the explanation.
Question 3 of 7In the before-define playground, why does line 12 print
truewhen the badge comes fromcreateElement()?Choose an answer to see the explanation.
Question 4 of 7Which name works in every browser?
Choose an answer to see the explanation.
Question 5 of 7What makes a custom element autonomous?
Choose an answer to see the explanation.
Question 6 of 7
customElements.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.
Question 7 of 7Your badge has a
titleproperty, thoughTeaBadgenever 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 withcustomElements.define(). extends HTMLElementgives your class a whole chain:HTMLElement,Element,Node, andEventTarget. 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.newstarts 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:
- Using custom elements, MDN.
- Classes: constructor, MDN.
- Window: customElements property, MDN.
- CustomElementRegistry: define() method, MDN.
- HTML Standard: The CustomElementRegistry interface, WHATWG.
- HTML Standard: Valid custom element name, WHATWG.
- Allow more characters in custom element names, WHATWG HTML pull request 7991.
- Chrome 143: Allow more characters in JavaScript DOM APIs, Chrome for Developers.
- Document.cpp, the custom element name check (WebKit-7625.2.8), WebKit.
- Document: createElement() method, MDN.
- HTML Standard: HTML element constructors, WHATWG.
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.