Custom Elements in HTML
How custom element tags behave in markup: naming rules, the upgrade when you define them, lifecycle order, and keeping content useful if scripts fail.
Custom Elements in HTML
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A custom element name must contain a hyphen, like `my-card`. `customElements.define` throws a `SyntaxError` for names without one.
- Until it is defined, `<my-card>` is a plain inline `HTMLElement` and `:not(:defined)` matches it. Its children are ordinary content, so the page still reads if the script never loads.
- When you call `define`, existing elements are upgraded: the constructor runs, then `attributeChangedCallback` for each observed attribute, then `connectedCallback`.
- If the script runs before the markup is parsed, `connectedCallback` fires at the opening tag, before children exist. In a test `children.length` was 0. Upgraded elements saw their children.
- Prefer progressive enhancement: write sensible HTML inside the tag, and let the element improve it. That is how a custom element degrades.
Your own tag, and what the browser does with it
HTML’s vocabulary is fixed, but you can add to it. Write <rating-stars value="4"> and the browser accepts it, with no error, no validation complaint, and no behaviour. Unknown tags with a hyphen are valid HTML, treated as generic inline elements. Add a JavaScript class and a customElements.define call and the tag gains behaviour.
This lesson is about how that looks from the markup side: the naming rule, when the tag comes alive, and how to keep the page working without it. Shadow DOM encapsulation, styling and component design are in the frontend roadmap’s web components lesson.
<rating-stars value="4">4 out of 5</rating-stars>
<script>
class RatingStars extends HTMLElement {
static observedAttributes = ["value"];
connectedCallback() { /* enhance */ }
}
customElements.define("rating-stars", RatingStars);
</script>
The name rule
The name must contain a hyphen, lowercase. customElements.define("nohyphen", …) threw a SyntaxError in Chromium 159, Firefox 159 and a WebKit build. This keeps your tags from colliding with anything HTML adds later.
Upgrade: markup first, behaviour later
Scripts often load after the markup. I tested that case, with the tag in the page and define called afterwards, in all three engines:
- Before
define, the element’s constructor was plainHTMLElement, it matched:not(:defined), and it was displayedinline. Its text stayed visible. - On
define, the element was upgraded in place: the constructor ran (and already saw 1 child),attributeChangedCallbackfired for the observed attribute (null -> hello), thenconnectedCallbackran, with children visible. customElements.whenDefined(name)resolved after that.
The :defined pseudo-class is the hook for covering the gap: rating-stars:not(:defined) can hold a placeholder size or fade, which the upgrade removes. In the test the opacity changed from 0.3 to 1 across define.
The other order: define first
If the script is above the tag and runs first, the parser creates the element as it reads its start tag. The result in all three engines was: constructor with children=0, attributeChangedCallback, then connectedCallback with children=0 and empty text. The children are parsed after the element is already connected. The constructor also saw no attributes (getAttribute was null), though attributes arrived through the callback. So don’t read children in the constructor or connected callback unless you know the script ran late. Use defer or a module script (see script loading), or wait for DOMContentLoaded.
Progressive enhancement
An undefined custom element shows its children. That makes a design principle: put real, useful HTML inside the tag, and let the element improve it. A <rating-stars> that wraps “4 out of 5” reads fine without script and with a screen reader. A <rating-stars value="4"></rating-stars> that is empty is blank until JavaScript renders, and blank forever if it fails. The same logic favours extending a native element’s job (a <button> inside, a <table> that sorts) over replacing it, since you inherit semantics, focus and the tree for free.
Custom elements are widely supported. web-features lists autonomous custom elements as Baseline, newly available in January 2020 and widely available since July 2022. Customized built-ins (is="…") are not in Safari, so avoid them.
What the video covers
Chris Ferdinandi’s “How to build your first Web Component” on Go Make Things (June 2024, about 9 minutes). The description links to source code and describes a simpler, faster way to build for the web, which fits the progressive-enhancement angle. I could not read a transcript, so I can’t describe what the component does. The upgrade, ordering and naming results are from my tests, not the video.
Where this fits
This follows template and slot. The group’s last lesson, contenteditable and drag and drop, looks at two more attributes that make a page interactive.
Check yourself
Why must a custom element name contain a hyphen?
To avoid clashing with current and future built-in elements, which never contain one. `customElements.define('nohyphen', ...)` threw a `SyntaxError` in all three engines I tested.
Your component reads `this.children` in `connectedCallback`, but it is empty when the script sits above the markup. Why?
The parser creates and connects the element at its start tag, before its children are parsed. In a test, defined-before-markup gave `children=0` and `textContent=""` in `connectedCallback`. Defining after the markup (or deferring, or waiting for `DOMContentLoaded`) saw the children.
How do you avoid a flash of unstyled content for a custom element that renders late?
Style the pre-upgrade state with `my-card:not(:defined)` (for example reserve space or lower opacity) and let the definition remove it. In a test the element matched `:not(:defined)` before `define` and not after.
What order do the callbacks run in when an existing element is upgraded?
Constructor, then `attributeChangedCallback` for each observed attribute that is present, then `connectedCallback`. In the test an observed `label` attribute reported `null -> hello` before connection.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.