Custom element registry
Learn the HTML side of the customElements API (naming, fallback).
What is a custom element?
A custom element lets you add your own tag to the HTML vocabulary. When the browser meets a tag like <profile-card>, it first treats it as an unknown element; once customElements.define() loads, it upgrades the element.
The naming rule is simple: lowercase, with at least one hyphen (-). profile-card is valid; ProfileCard has uppercase letters and card has no hyphen, so both are invalid. This avoids clashes with built-in tags.
Fallback content and HTMLUnknownElement
Before JavaScript loads, the browser treats an undefined custom element as HTMLUnknownElement. The content stays visible; only the special behaviour and styles are missing.
That's why putting fallback content inside a custom element is good practice. Even without the script, the user sees something meaningful: when a <profile-card> holds an <img>, an <h2> and a <p>, the card stays readable without JS.
Exercise Write a profile-card with fallback content
Write a simple <profile-card> custom element. It should contain:
- Opening tag:
<profile-card> - An
<img>with non-empty src and alt (avatar) - An
<h2>with non-empty content (name) - A
<p>with non-empty content (bio) - Closing tag:
</profile-card>
The card must stay readable even without JS.
Show example solution
<profile-card>
<img src="/user/alex/avatar.png" alt="Alex Morgan avatar">
<h2>Alex Morgan</h2>
<p>Product designer, lives in London.</p>
</profile-card>
Test yourself
-
Which is a valid custom element name?
- ProfileCard
- usercard
- user-card
- User-Card
Show answer
user-card — Correct. user-card is lowercase and has a hyphen; it fits the rule.
-
Complete the custom element tag
<____>Alex Morgan</profile-card>Show answer
<profile-card>Alex Morgan</profile-card> -
Match each custom element name to its purpose
- profile-card
- User details
- weather-widget
- Weather report
- cart-item
- Cart product
- rating-stars
- Rating display