completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

What are web components?

A web component is an HTML tag you make yourself. Build your first one, meet the three browser features behind it, and see who uses them.

By the end, you can
  • 01
    Make a tag of your ownPick a name with a hyphen, write a class for it, and register the two with customElements.define().
  • 02
    Name the three featuresTell custom elements, shadow DOM, and templates with slots apart, and say which standard each one is written in.
  • 03
    Know what they are, and who uses themExplain what web components are and aren't, and find custom tags on real sites such as MDN and YouTube.

An HTML tag you make yourself

You already know a lot of HTML tags. <p> holds a paragraph. <button> can be clicked. <video> plays a film, with its own play button and timeline. You write one short tag, and the browser knows what to do with it.

Now say you run a tea shop's website. Every tea on the menu needs the same little label: its name, and how many minutes to brew it. HTML has no tag for that. You could copy the same few lines of HTML for every tea. Or you could make a new tag, <tea-label>, and use it like any other.

That second idea is what a web component is. Here is a whole one, on a page of its own:

<tea-label name="Green tea" minutes="3"></tea-label> <script>  class TeaLabel extends HTMLElement {    connectedCallback() {      const name = this.getAttribute("name");      const minutes = this.getAttribute("minutes");      this.textContent = `${name}: brew for ${minutes} minutes`;    }  }   customElements.define("tea-label", TeaLabel);</script>
ResultLoading…
  • Line 1 uses the new tag, just like a built-in one. It has two attributes: name and minutes.
  • Line 4 makes a class called TeaLabel. A class is a blueprint for objects. extends HTMLElement means "start with everything a plain HTML element already has". So every tea label can already sit on a page, have attributes, and hold text.
  • Line 5 is a method with a special name, connectedCallback. The browser calls it when the tag is put on the page. Stage 2 of this course is all about methods like this one.
  • Lines 6 and 7 read the two attributes. this is the tag itself.
  • Line 8 sets the tag's text to Green tea: brew for 3 minutes.
  • Line 12 is the line that makes it all work. customElements.define() tells the browser: "from now on, the tag tea-label is built with the class TeaLabel."

The result under the code is the real page, running in your browser. It shows Green tea: brew for 3 minutes. Press Edit & run, change minutes="3" to minutes="5", and the result changes as you type.

Making a new tag. A name tag says tea-label. A class card says TeaLabel. Arrows from both lead to define(). An arrow from define() leads to a page that shows Green tea: brew for 3 minutes.tea-label1. a nameTeaLabel2. a classdefine()3. registerpageGreen tea:brew for 3 minutes
A name with a hyphen, a class that says what the tag does, and customElements.define() to join them. After that, the page shows Green tea: brew for 3 minutes.

You write the class once. Then you can use the tag as often as you like. In this menu, the class lives in its own file, tea-label.js. Click the second tab to see it. It's the same class, with the same define() line at the end.

One class, three labelsPop out in the code editor (opens in a new tab)HTML
<h1>Today's teas</h1><ul>  <li><tea-label name="Green tea" minutes="3"></tea-label></li>  <li><tea-label name="Black tea" minutes="4"></tea-label></li>  <li><tea-label name="Mint tea" minutes="5"></tea-label></li></ul> <script src="tea-label.js"></script>
ResultLoading…

Lines 3 to 5 use <tea-label> three times, each inside a normal <li>. Line 8 loads the class. The page shows three labels, each with its own tea and time. Your tag mixes with HTML's own tags as if it had always been there.

Real-life analogyA new drink on the tea shop's menu

A tea shop invents a new drink. The owner writes its name on the menu board and pins the recipe card up in the kitchen. From then on, any customer can order it by name. Nobody has to explain how to make it again: the staff follow the card.

In real life: The drink's name on the menu board
In JavaScript: The tag name tea-label
In real life: The recipe card in the kitchen
In JavaScript: The class TeaLabel
In real life: Writing the name on the board and pinning up the recipe
In JavaScript: customElements.define("tea-label", TeaLabel)
In real life: A customer ordering it by name
In JavaScript: Writing <tea-label> in your HTML
In real life: The staff making the drink from the recipe
In JavaScript: The browser building the tag from your class
The main idea

A web component is an HTML tag you make yourself. You pick a name with a hyphen, write a class that says what the tag does, and register the two with customElements.define(). After that, the browser treats your tag like one of its own, on any page.

Before the browser knows your tag

What if the page uses <tea-label> but never defines it? Maybe the script hasn't loaded yet, or someone forgot it. Does the page break?

No. Try it:

A tag the browser doesn't know yetPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label> <script>  const label = document.querySelector("tea-label");  console.log(customElements.get("tea-label"));  console.log(label.matches(":defined"));</script>
ResultLoading…
  • Line 1 uses the tag, with the words Green tea written inside it this time.
  • Line 4 finds the tag on the page with document.querySelector().
  • Line 5 asks the browser's list of known tags about tea-label. That list is called the registry, and customElements is how you reach it. get() gives back the class for a name, or undefined when there isn't one. Here it prints undefined.
  • Line 6 asks whether the tag matches :defined, a CSS selector for elements the browser knows how to build. It prints false.

And the result shows Green tea. The browser keeps the unknown tag, shows the text inside it, and waits. It's like a seat at a dinner table with a name card on it: the seat is kept, and the guest sits down when they arrive.

Switch between the two choices below. The page is the same each time. Only line 3, which loads the class, comes and goes:

Playground: define the tag, or don't
A tea label, with or without its classPop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label> <script>  const label = document.querySelector("tea-label");  console.log(label.matches(":defined"));</script>
ResultLoading…
Try it yourself
The page shows "Green tea" and the console prints false

No class for tea-label yet. The browser keeps the tag and shows the text inside it, Green tea. :defined doesn't match, so the console says false.

Both choices are the same page. The only difference is line 3, which loads the tag's class from tea-label.js (the second tab). The result runs in a fresh page each time, so nothing from one run leaks into the next.

Now the most surprising part. The definition can arrive after the tag is already on the page. In this example, the class only gets registered when you click the button. Click Define tea-label in the result:

Define the tag after it's on the pagePop out in the code editor (opens in a new tab)HTML
<tea-label name="Green tea" minutes="3">Green tea</tea-label><button>Define tea-label</button> <script>  class TeaLabel extends HTMLElement {    connectedCallback() {      const name = this.getAttribute("name");      const minutes = this.getAttribute("minutes");      this.textContent = `${name}: brew for ${minutes} minutes`;    }  }   const button = document.querySelector("button");  button.addEventListener("click", () => {    customElements.define("tea-label", TeaLabel);    button.disabled = true;  });</script>
ResultLoading…
  • Line 1 puts the tag on the page. Line 2 adds a button.
  • Lines 5 to 11 are the same TeaLabel class as before. Making a class doesn't register it.
  • Lines 13 and 14 find the button and run some code when it's clicked.
  • Line 15 registers the class, only once you click. Line 16 turns the button off, because a name can only be registered once. A second define() for the same name would throw an error.

When you click, the label changes from Green tea to Green tea: brew for 3 minutes. The browser found the tag that was already waiting and turned it into a real TeaLabel. This is called an upgrade.

Before and after define. Before: the page shows plain Green tea, because tea-label isn't defined yet. An arrow labelled define() leads to after: the same tag now shows Green tea: brew for 3 minutes.beforeGreen teanot defined yetdefine()afterGreen tea:brew for 3 minutesupgraded
Before the click, the browser shows the text inside the tag. The click runs define(), and the browser upgrades the tag that is already on the page.

Upgrades are why the order of your scripts doesn't break anything. HTML can arrive first, and the class can load later. Until then, the reader sees the text inside the tag. Lesson 2.4 shows how to style tags while they wait.

Every custom tag has a hyphen

Look at the names so far: tea-label, tea-card. Each has a hyphen. That's not style. It's a rule. A name without one fails:

A name with no hyphen (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
class TeaLabel extends HTMLElement {}

customElements.define("tealabel", TeaLabel);

Line 3 tries to register the name tealabel. The browser stops with a SyntaxError. In Chrome, the message reads "tealabel" is not a valid custom element name.

Why the hyphen? HTML makes a promise: it will never add a built-in tag with a hyphen in its name. So:

  • HTML's own tags never have a hyphen: <p>, <button>, <video>.
  • Your tags always do.
  • The two can never clash, even when HTML adds new tags in ten years.

Think of HTML's tags as words in a dictionary. Words with a hyphen are kept free for you, so you can never pick a word the dictionary adds later.

Here is the whole list of rules from the HTML standard. A custom tag's name must:

  • start with a lowercase letter, a to z;
  • contain at least one hyphen;
  • have no capital letters, A to Z;
  • have no spaces, no slash (/), and no >;
  • not be one of eight names that SVG and MathML already use, such as font-face and missing-glyph.

Anything else goes. Digits, dots, even letters from other languages and emoji are fine after the first letter: tea-cup-2 and math-α both work. Type some names and see which ones the browser would take:

Playground: will the browser take this name?
Register a class under your nameJavaScript
class TeaLabel extends HTMLElement {}
customElements.define("tea-label", TeaLabel);
console.log("Accepted");
What define() does

It registers the tag.

The browser accepts this name.

Try it yourself
Accepted

The browser accepts this name.

The checker follows the HTML standard's rules for custom element names. Start with a lowercase letter and include a hyphen. Leave out capital letters, spaces, slashes, and >, and the eight names SVG and MathML use.

One more thing. The tag name and the class name are different things. The tag is tea-label, lowercase with a hyphen. The class is TeaLabel, a normal JavaScript class name. define() joins them.

Three features, three standards

"Web components" isn't one feature. It's a name for three browser features that work well together. So far you've used the first one.

  • Custom elements: your own tags, with a class behind each. That's customElements.define().
  • Shadow DOM: a private inside for an element. The page's CSS rules can't pick out what's inside, and the element's own CSS rules don't leak out to the page.
  • Templates and slots: HTML you write once and copy many times (<template>), and holes in a component that the page fills in (<slot>).

You can use each one on its own. Here is a small taste of the other two.

Shadow DOM: a private inside

The DOM is the browser's tree of everything on the page. A shadow root is a small, separate tree that belongs to one element. This page colors every paragraph red, then puts one paragraph inside a shadow root:

The page's p rule can't pick a p inside a shadow rootPop out in the code editor (opens in a new tab)HTML
<style>  p { color: red; }</style> <p>Our teas</p><tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      const shadow = this.attachShadow({ mode: "open" });      shadow.innerHTML = "<p>Green tea</p>";    }  }   customElements.define("tea-card", TeaCard);</script>
ResultLoading…
  • Line 2 makes every <p> on the page red.
  • Line 5 is a normal paragraph, Our teas. Line 6 is a new tag, <tea-card>.
  • Line 10 is the constructor, which runs when each tea card is made. Line 11, super(), lets HTMLElement set the element up first.
  • Line 12 gives the card a shadow root with attachShadow(). mode: "open" lets other code reach it later through element.shadowRoot.
  • Line 13 puts a paragraph, Green tea, inside the shadow root.

In the result, Our teas is red. Green tea isn't, even though it's a <p> too. The selector p on line 2 only finds paragraphs in the page's own tree, not inside a shadow root. A shadow root is like the kitchen behind a tea shop's counter. The signs on the shop floor don't apply in there. And the kitchen's mess doesn't spill into the shop.

One thing does pass in. Some styles are inherited: an element takes them from the element around it, like the text color and the font. If the page made the whole <tea-card> red, Green tea would turn red too. Stage 4 covers styling across the boundary in full.

Templates: HTML to copy

A <template> holds HTML that isn't shown. It waits until your code copies it, like a rubber stamp waiting to be pressed:

One template, stamped twicePop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li>Tea</li></template> <ul></ul> <script>  const template = document.querySelector("#tea-row");  const list = document.querySelector("ul");  for (const tea of ["Green tea", "Black tea"]) {    const row = template.content.cloneNode(true);    row.querySelector("li").textContent = tea;    list.append(row);  }</script>
ResultLoading…
  • Lines 1 to 3 are the template: one list item. The page doesn't show it.
  • Line 5 is an empty list. Lines 8 and 9 find the template and the list.
  • Line 10 loops over two teas. Line 11 makes a fresh copy of the template's content. cloneNode(true) copies everything inside, too.
  • Line 12 writes the tea's name into the copy. Line 13 adds it to the list.

The result shows two items, Green tea and Black tea. Components often keep their inside HTML in a template like this, and stamp a copy into each new element.

Slots: holes the page fills

A <slot> is a hole in a shadow root. Whatever the page writes inside your tag shows up in that hole. Think of a picture frame: the frame belongs to the component, and the photo belongs to the page.

The page's text goes into the slotPop out in the code editor (opens in a new tab)HTML
<tea-card>Green tea</tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      const shadow = this.attachShadow({ mode: "open" });      shadow.innerHTML = "<p>Today's tea: <slot></slot></p>";    }  }   customElements.define("tea-card", TeaCard);</script>
ResultLoading…
  • Line 1 writes Green tea inside <tea-card>.
  • Line 7 gives the card a shadow root, as before.
  • Line 8 fills it with a paragraph that has a <slot> in the middle.

The result shows Today's tea: Green tea. The words Today's tea: come from the component. Green tea comes from the page, shown in the slot. Change line 1 to another tea, and the card follows.

Who writes the rules

Each feature is written down in a standard: a long, exact document that every browser follows. That's why your tag works the same in Chrome, Firefox, and Safari. Three standards hold the pieces:

Three standards, three shelves. HTML: customElements, <template>, <slot>. DOM: attachShadow(), shadow trees, events. CSS: :host, ::slotted(), ::part().HTMLcustomElements<template><slot>DOMattachShadow()shadow treeseventsCSS:host::slotted()::part()
The HTML Standard holds custom elements, <template>, and <slot>. The DOM Standard holds shadow trees and events. CSS Shadow Module holds the selectors for styling them.
  • The HTML Standard holds custom elements, the registry, <template>, and <slot>.
  • The DOM Standard holds shadow trees, attachShadow(), and how events travel through them.
  • CSS Shadow Module Level 1 holds the CSS selectors for components, such as :host, ::slotted(), and ::part(). It used to be two specs, CSS Scoping and CSS Shadow Parts, and older articles still use those names.

Sort each piece onto its shelf. You'll meet the CSS ones properly in stage 4.

Which standard is it in?
  • customElements.define()
  • customElements.get()
  • <template>
  • <slot>
  • attachShadow()
  • element.shadowRoot
  • :host
  • ::part()
  • ::slotted()
Try it yourself
0 of 9 correct

Sort each piece by the standard that defines it.

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

The browser builds its own tags the same way

Here's a secret. Some of HTML's own tags are built from these same pieces. A slider and a "show more" box each hide a small shadow tree inside:

Built-in tags keep their insides privatePop out in the code editor (opens in a new tab)HTML
<input type="range"><details>  <summary>More teas</summary>  Oolong and white tea.</details> <script>  console.log(document.querySelector("input").shadowRoot);  console.log(document.querySelector("details").shadowRoot);</script>
ResultLoading…
  • Line 1 is a slider, <input type="range">.
  • Lines 2 to 5 are a <details> box. Click More teas in the result to open it.
  • Lines 8 and 9 ask each one for its shadow root. Both print null.

null means "nothing your code may see". The browser's own shadow roots are called user-agent shadow roots (the user agent is the browser), and page code can't open them. But Chrome's DevTools can show them:

  1. Open DevTools: right-click the page and choose Inspect.
  2. Open Settings: click the gear button at the top of DevTools.
  3. Under Preferences, find Elements and turn on Show user agent shadow DOM. Close Settings.
  4. In the Elements panel, find a <details> element and open it with the small arrow.

Under the <details> box from the example, Chrome shows this:

Inside <details>, in Chrome's Elements panel (shortened)Text
<details>
  #shadow-root (user-agent)
    <slot id="details-summary"></slot>
    <slot id="details-content"></slot>
    <style>…</style>
  <summary>More teas</summary>
  "Oolong and white tea."
</details>

Line 2 is the hidden shadow root. Lines 3 and 4 are two slots. Your <summary> goes into the first slot, and the rest of the text goes into the second. That's the same trick as the tea card's slot. The HTML standard says this is the goal: to explain HTML's own elements with the same tools page authors get. When you build a web component, you build the way the browser does.

What web components are, and what they aren't

The name "web components" makes many people think of React or Vue components. They're different things. Read this table across: what people often say, then what's true.

Web components, myth and fact
What people sayWhat's true
They're a framework, like React.No. They're three features built into every browser. There's nothing to install.
They replace React or Vue.No. Your tag works inside React, Vue, Angular, and Svelte, the same way a <button> does.
Every one needs shadow DOM.No. The tea-label in this lesson has no shadow root, and it's still a web component.
Every part of an app should be one.They fit best for parts many pages or apps share, like a star rating, a tab bar, or a date picker.
They need a library such as Polymer.No. You can write them with plain JavaScript. Libraries like Lit only save typing.

The biggest difference is where they live. A React component only works inside React. A web component is an HTML tag, and every framework knows how to put an HTML tag on a page. React 19 added full support for custom elements, so it passes every check on the Custom Elements Everywhere test site, as Vue, Angular, and Svelte do.

One file, tea-label.js, defines the tag. Arrows lead from it to four pages, HTML, React, Vue, Angular, and each page uses the same tea-label tag.tea-label.js<tea-label>HTML<tea-label>React<tea-label>Vue<tea-label>Angular
One file defines the tag. A plain HTML page uses it, and so do pages built with React, Vue, and Angular. To each of them, <tea-label> is one more HTML tag.

That makes web components best for pieces many projects share. A tab bar, a star rating, a date picker, or a whole design system can be written once and used by every team, whatever they build with. A page that only one app ever shows gains less. It's like a standard light switch: it fits in any house, whoever built the house.

Two more things they aren't. They aren't a library you install: they're built into every browser. And they don't need shadow DOM. The tea-label from the start of this lesson has no shadow root, and it's still a web component. Many people now write "HTML web components" like it: a custom tag that wraps normal HTML and adds a little behavior.

Who builds with web components

Web components aren't a corner of the web. In Chrome, about one page load in five defines a custom element, and nearly one in four attaches a shadow root. Some of the best-known apps are built with them:

  • Photoshop on the web. Adobe built the whole app from web components, made with the Lit library. Its buttons, menus, and other controls come from Adobe's Spectrum Web Components, which work with any framework or none.
  • Microsoft Edge. Parts of Edge's own interface are built with web code. Microsoft rebuilt them on a set of web components, with HTML first and much less JavaScript at startup. The first one, the Browser Essentials panel, became 42% faster.
  • MDN. The documentation site rebuilt its front end. Its pages are mostly plain HTML and CSS, and the interactive parts, like the search button and the theme switcher, are web components.
  • Firefox. The tabs, buttons, and menus around every Firefox page are built with markup and JavaScript, like a web page. In 2019 Mozilla finished moving them all to web components. They replaced an older system called XBL: about 300 pieces and 50,000 lines of code.
  • YouTube and GitHub. YouTube's page is a tree of custom tags starting with <ytd-app>. GitHub shows dates with a <relative-time> tag and copy buttons with <clipboard-copy>.

Lit, the library Photoshop and MDN use, also lists Chrome's DevTools, Reddit, and the Microsoft Store among its users. You'll learn Lit in stage 8, after you know what it does for you.

Custom elements, shadow DOM, and slots have worked in every major browser since January 2020, when Edge moved to Chromium. You don't need a polyfill: extra code that fakes a missing feature.

A map of this course

This course goes from the tag you just made to how browsers build components inside. It follows one order: use, then build, then ship, then look inside.

  • Use (stage 1): what works today, and how to use components other people made.
  • Build with the platform (stages 2 to 7): custom elements, shadow DOM, styling, accessibility, forms, and building components well, with no library at all.
  • Lit (stage 8): the most popular library for writing web components.
  • Ship (stages 9 to 13): server rendering, frameworks, testing and publishing, design systems, and big apps.
  • Look inside (stages 14 and 15): read how Chrome, Firefox, and Safari build components, then build a small Lit of your own.
  • Projects (stage 16): put it all together.

Along the way you'll build one project: a UI kit for the tea shop. From stage 2 on, each lesson adds to it, so the same labels, cards, and buttons get styled, made accessible, tested, and shipped. Here are all 16 stages:

  1. Getting started (9 lessons). What web components are, where they stand in 2026, and how to use components other people built.
  2. Custom elements (16 lessons). Define your own elements: the class, the lifecycle, upgrades, the registry, and a clean public API.
  3. Shadow DOM, templates, and slots (20 lessons). Give a component a private inside, put the user's content where it belongs, and handle events and focus across the boundary.
  4. Styling web components (14 lessons). Style a component from the inside, and give the people using it a clear, safe way to style it from the outside.
  5. Accessible components (13 lessons). Make components that screen readers, keyboards, and every visitor can use, across shadow roots.
  6. Forms (9 lessons). Make components that join forms like native inputs: values, validation, reset, restore, and submission.
  7. Building components well (10 lessons). Reactive rendering, a toolkit of your own, and patterns for data and composition, before reaching for a library.
  8. Lit (14 lessons). Lit is the most used web components library. Learn it from the first component to publishing.
  9. Server rendering (10 lessons). Send components as HTML with declarative shadow DOM, hydrate them, and use them with server frameworks.
  10. Frameworks and libraries (11 lessons). Use web components inside frameworks, make web components from frameworks, and choose a library.
  11. Testing, tooling, and publishing (12 lessons). Test components in real browsers, describe them with a manifest, and publish them safely.
  12. Design systems (9 lessons). Build and run a design system on web components: specs, tokens, themes, docs, and teams.
  13. Applications and performance (12 lessons). Build whole applications from web components, keep them secure, and make them fast.
  14. Under the hood (25 lessons). How browsers and libraries implement custom elements, shadow DOM, slots, events, styles, forms, and accessibility, read from the source.
  15. Build it yourself, and the standards behind it (16 lessons). Build your own component framework, read the specs, and follow how web components were made and where they're going.
  16. Projects (14 lessons). Guided projects and a capstone that use the whole course.

Find the custom tags on any page

Now look for web components on real websites. A tag with a hyphen in its name is a custom tag. The only exceptions are the eight SVG and MathML names from the rules above, like font-face, and you'll rarely meet them. This page lists every hyphenated tag it has:

List every custom tag on a pagePop out in the code editor (opens in a new tab)HTML
<h1>Tea shop</h1><tea-label name="Green tea" minutes="3"></tea-label><tea-card></tea-card> <script>  const names = new Set();  for (const element of document.querySelectorAll("*")) {    if (element.localName.includes("-")) names.add(element.localName);  }  console.log([...names].join(", "));</script>
ResultLoading…
  • Lines 1 to 3 are the page: a heading and two custom tags.
  • Line 6 makes a Set, a list that keeps each value only once.
  • Line 7 goes through every element on the page. querySelectorAll("*") matches them all.
  • Line 8 checks each tag's name. localName is the tag's name in lowercase. If it has a hyphen, the name goes into the set.
  • Line 10 prints the names with commas between them: tea-label, tea-card.

Now try it on a real site. Open MDN's Web Components page, open DevTools, and click the Console tab. Paste lines 6 to 10 and press Enter:

Paste this into the Console on any sitePop out in the code editor (opens in a new tab)JavaScript
const names = new Set();
for (const element of document.querySelectorAll("*")) {
  if (element.localName.includes("-")) names.add(element.localName);
}
console.log([...names].join(", "));

These are lines 6 to 10 from above. Line 5 prints the list. You'll get a long list of custom tags. Try it on YouTube and GitHub too. The tags only show the top layer: a component can hide more custom tags inside its own shadow root.

Common mix-ups

  • "Web components are a framework." No. They're three features built into every browser: custom elements, shadow DOM, and templates with slots.
  • "Web components replace React." No. They work inside React, Vue, Angular, and Svelte, like any HTML tag. They fit best for pieces many projects share.
  • "Every web component needs shadow DOM." No. Shadow DOM is optional. A custom tag that wraps normal HTML is still a web component.
  • "An unknown tag breaks the page." No. The browser keeps it, shows the text inside, and upgrades it when the class arrives.
  • "Web components means Polymer and HTML Imports." No. Polymer was an early library, and its last release came out in 2024. HTML Imports were an early draft that only Chrome had, and Chrome removed it in 2020.
  • "You need polyfills." No. Every major browser has had custom elements, shadow DOM, and slots since 2020.

Practice exercises

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

Exercise 1 · Warm-upAsk before it's defined

What does the console print?

<tea-label name="Black tea" minutes="4">Black tea</tea-label>

<script>
  console.log(customElements.get("tea-label"));
</script>

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

    Exercise 2 · Warm-upFour names

    The code tries to register four names. Only one works. Which?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const names = ["tea-cup", "teacup", "Tea-Cup", "font-face"];
    
    for (const name of names) {
      try {
        customElements.define(name, class extends HTMLElement {});
        console.log(name, "works");
      } catch {
        console.log(name, "fails");
      }
    }

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

      Exercise 3 · PracticeA price tag

      Make <tea-price amount="4"> show Price: 4. Write your class in the script. What does your page show?

      <tea-price amount="4"></tea-price> <script>  // Write a TeaPrice class here, then register it as tea-price.  // It should show the text "Price: 4".</script>
      ResultLoading…

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

        Exercise 4 · PracticeFind the bug

        This code throws when it runs. Which kind of error, and how do you fix it?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        class TeaPrice extends HTMLElement {
          connectedCallback() {
            this.textContent = "Price: 4";
          }
        }
        
        customElements.define("teaprice", TeaPrice);

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

          Exercise 5 · ChallengeInside a slider

          In Chrome, inspect this slider with user-agent shadow DOM turned on. Inside its shadow root is a div with id="track". What's the id of the div inside the track?

          <input type="range">
          ResultLoading…

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

            Exercise 6 · ChallengeMDN's tags

            Run the custom tag finder on developer.mozilla.org. What do the names of MDN's own tags start with?

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

              Check your understanding

              For each question, think about the three pieces: a name with a hyphen, a class, and the line that joins them.

              The web components quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Which of these names can you give a custom element?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does the first console line of the unknown tag example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-label name="Green tea" minutes="3">Green tea</tea-label>
                
                <script>
                  const label = document.querySelector("tea-label");
                  console.log(customElements.get("tea-label"));
                  console.log(label.matches(":defined"));
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 8A page has three <tea-label> tags, and customElements.define() for them runs one second later. What happens to the three tags?

                Choose an answer to see the explanation.

              4. Question 4 of 8Which three browser features does the name "web components" cover?

                Choose an answer to see the explanation.

              5. Question 5 of 8Does a web component need shadow DOM?

                Choose an answer to see the explanation.

              6. Question 6 of 8In the shadow DOM example, what color is the text Green tea?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  p { color: red; }
                </style>
                
                <p>Our teas</p>
                <tea-card></tea-card>
                
                <script>
                  class TeaCard extends HTMLElement {
                    constructor() {
                      super();
                      const shadow = this.attachShadow({ mode: "open" });
                      shadow.innerHTML = "<p>Green tea</p>";
                    }
                  }
                
                  customElements.define("tea-card", TeaCard);
                </script>

                Choose an answer to see the explanation.

              7. Question 7 of 8Which standard defines the ::part() selector?

                Choose an answer to see the explanation.

              8. Question 8 of 8Microsoft rebuilt parts of Edge's own menus on a set of web components. Why did they get faster?

                Choose an answer to see the explanation.

              Key takeaways

              • A web component is an HTML tag you make yourself: a name with a hyphen, a class, and customElements.define().
              • An unknown tag isn't an error. The browser shows its text, then upgrades it when the class arrives.
              • Every custom tag has a hyphen, so it can never clash with HTML's own tags.
              • The name covers three features: custom elements, shadow DOM, and templates with slots. You can use each on its own.
              • The HTML Standard, the DOM Standard, and CSS Shadow Module write the rules, so they work the same in every browser.
              • They work in any page and any framework, and Photoshop, Edge, MDN, Firefox, and YouTube are built with them.

              Remember the one-liner.
              A web component is your own HTML tag: a name with a hyphen, a class that says what it does, and one line that tells the browser.

              Sources

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

              Coming next: Web components in 2026. What works in every browser now, what changed in the last few years, and why older tutorials can lead you wrong.

              CompleteFrontend Clear concepts. Working examples.