{"canonical_url":"https://engineer.company/glossary/web-components/","content_markdown":"# Web components\n\n## What it is\n\nWeb components, also written Web Components with capitals, is the usual name for\na group of browser features that let authors define their own HTML elements. A\npage then uses such an element like any other tag. The standards speak of the\nparts by their own names: custom elements and the `template` and `slot` elements\nin the HTML Standard, and shadow trees in the DOM Standard. The collective name\nis the title of a W3C Working Group Note of 24 July 2014,\n[_Introduction to Web Components_](https://www.w3.org/TR/components-intro/),\nwhich the W3C has since discontinued and marked as a document that should not be\nreferenced.\n\nA custom element is defined by a JavaScript class that extends `HTMLElement` and\nis registered under a name with `customElements.define()`. The definition tells\nthe HTML parser how to construct the element and how it should react to changes,\nand from then on the element can be created from markup, with\n`document.createElement()` or with `new`. Its name starts with a lower-case\nASCII letter, contains no upper-case ASCII letters and must contain a hyphen.\nThe hyphen keeps custom names apart from the language itself: the HTML Standard\nsays that HTML, SVG and MathML will not gain any element whose name contains a\nhyphen.\n\nThere are two kinds. An autonomous custom element, such as the standard's own\n`\u003cflag-icon country=\"nl\"\u003e`, starts from a plain element with no built-in\nmeaning. A customized built-in element extends an existing one: a class that\nextends `HTMLButtonElement`, registered with `{ extends: \"button\" }` and used as\n`\u003cbutton is=\"plastic-button\"\u003e`, keeps everything that makes a button a button,\nincluding focus behaviour, form submission and the `disabled` attribute.\n\nA shadow tree is a separate tree of nodes attached to an element, which is\ncalled its host; the DOM Standard calls the host's ordinary tree the light tree.\n`attachShadow()` creates a shadow root in open or closed mode, and only in open\nmode does the host's `shadowRoot` property return it. A `slot` element in the\nshadow tree marks where the host's own children appear. It shows the nodes\nassigned to it, or its own contents when there are none, and a named slot takes\nthe children whose `slot` attribute carries its name. The `template` element\nholds a fragment of HTML that is not rendered and that a script can clone. With\na `shadowrootmode` attribute, a `template` represents a declarative shadow root,\nso a shadow tree can also be written straight into the markup.\n\n## Why it matters\n\nA made-up tag used to be of little use: the HTML Standard looks back on such\nelements as invalid and of little practical use. A custom element is a full\nmember of the document. The parser constructs it, the DOM methods create it, and\nits class decides what happens when its attributes change or when it enters or\nleaves a page.\n\nThe definition does not have to arrive first. An element the parser has already\ncreated becomes a custom element once a definition for its name is registered,\nand the HTML Standard calls this upgrading. Until then the element is treated as\nan undefined element, much like a `span`, so the text and links inside it are\nshown as they are. The standard says in so many words that upgrades allow the\ncontent of a custom element to be progressively enhanced.\n\nA custom element can also take part in forms and in the accessibility tree. A\nclass that sets `static formAssociated = true` and calls `attachInternals()`\ngets an `ElementInternals` object, and `setFormValue()` on that object gives the\nelement a value that its form submits like any other control's. The same object\nsets a default ARIA role and default ARIA states, which apply unless the page\nauthor overrides them with the `role` attribute or the matching `aria-*`\nattributes, and it can hold custom states that style sheets match with the\n`:state()` pseudo-class.\n\nFor a team, the shadow tree is what makes a component self-contained: ordinary page\nselectors do not cross into its internal shadow tree, and the component decides\nwhich parts to expose for outside styling. Inherited values and custom properties\ncan still enter, and slotted light-tree content remains subject to page selectors. Where several libraries share a page, the\nHTML Standard offers scoped registries, created with\n`new CustomElementRegistry()`, so that their elements can coexist without the\nlibraries having to coordinate their names.\n\n## What it looks like in practice\n\nA product card shows the parts working together. The page holds the content as\nordinary markup, with a `slot` attribute on the element that should go into a\nnamed slot:\n\n```html\n\u003cproduct-card\u003e\n  \u003cspan slot=\"name\"\u003eOak stool\u003c/span\u003e\n  \u003ca href=\"/shop/oak-stool/\"\u003eSee the details\u003c/a\u003e\n\u003c/product-card\u003e\n\u003cscript type=\"module\" src=\"product-card.mjs\"\u003e\u003c/script\u003e\n```\n\nThe module defines the element. The template is built once, and every card gets\nits own copy of it in an open shadow root:\n\n```js\nconst template = document.createElement(\"template\");\ntemplate.innerHTML = `\n  \u003ch2 part=\"title\"\u003e\u003cslot name=\"name\"\u003eUnnamed product\u003c/slot\u003e\u003c/h2\u003e\n  \u003cslot\u003e\u003c/slot\u003e\n`;\n\nclass ProductCard extends HTMLElement {\n  constructor() {\n    super();\n    const root = this.attachShadow({ mode: \"open\" });\n    root.append(template.content.cloneNode(true));\n  }\n}\n\nif (!customElements.get(\"product-card\")) {\n  customElements.define(\"product-card\", ProductCard);\n}\n```\n\nThe page styles the title through the one part the component exposes:\n\n```css\nproduct-card::part(title) {\n  font-size: 1.25rem;\n}\n```\n\nBefore `product-card.mjs` has run, the card is an undefined element and the\nreader sees the product name and the link as plain inline content. When the\nmodule runs, `define()` registers the class and the card already in the page is\nupgraded. Its constructor attaches a shadow root and fills it with a clone of\nthe template's contents. The `span` is assigned to the slot called `name` and\nappears inside the heading. The link has no `slot` attribute, so it goes to the\nunnamed default slot. A card without a name shows the slot's own contents,\n“Unnamed product”, in its place. The `customElements.get()` check keeps a second\ncopy of the module, arriving in another bundle, from making `define()` throw.\n\nShared components help only if people use them, and this site's portfolio has a\ncase about that.\n[The iOS 26 “Liquid Glass” design system](/portfolio/designed-an-ios-26-liquid-glass-design-system/)\nstarts from a UI in which every new screen reinvents its own buttons, badges and\ncards, each a little different, until every change means touching five bespoke\nversions. The answer described there is a canonical set of components that every\nscreen composes from, among them Card, Label, Button, GlassIconButton and\nDirectoryGrid, with lint rules that reject a hand-rolled badge or chip and point\nto the canonical component. The page does not say whether those components are\ncustom elements, but the discipline carries over: one definition per component,\nkept in force by tooling rather than by a reviewer's memory. The custom element\nregistry enforces the first half by refusing a second definition for a name.\n\n## Where it goes wrong\n\n**A hyphenated name stands in for a role.** “An autonomous custom element does\nnot have any special meaning: it represents its children,” says the HTML\nStandard. Its `taco-button` example shows the cost: to act as a button, the\nelement needs a `tabindex`, the ARIA role `button`, an accessible name,\n`aria-disabled`, key handlers that turn Enter and Space into clicks, and styles\nfor the disabled state. Even then, a custom element cannot declare default focus\nbehaviour, so `tabindex=\"0\"` may not match how buttons behave on the platform.\nWhere the element builds on an existing one, the standard says extending a\nbuilt-in element reduces the work for both its author and the people using it.\nFor an autonomous element, set its default role and states through\n`ElementInternals` rather than leaving them to every page that uses it.\n\n**The constructor does the work.** The HTML Standard sets rules for custom\nelement constructors: `super()` with no arguments comes first, the constructor\nmust not look at the element's attributes or children, because an element\ncreated rather than upgraded has none, and the element must not gain attributes\nor children of its own. A constructor that breaks these rules can produce an\nelement that the parser or the DOM methods cannot create. Use the constructor\nfor initial state, default values, event listeners and the shadow root, and move\nfetching and rendering to `connectedCallback`.\n\n**`connectedCallback` is expected to run once.** It can run more than once. By\ndefault, moving an element runs `disconnectedCallback` and then\n`connectedCallback`, so the element resets its state as if it had been removed\nand inserted again. Guard set-up that must happen only once with a flag, and\nundo in `disconnectedCallback` what `connectedCallback` started. If an element\nshould keep its state when it is moved with `moveBefore()`, define\n`connectedMoveCallback`, whose presence alone replaces the default pair, even\nwith an empty body.\n\n**A name is defined twice.** `customElements.define()` throws a\n`NotSupportedError` when the name or the class is already registered, and a\n`SyntaxError` when the name is not valid, for example because it has no hyphen\nor contains a capital letter. Check with `customElements.get()` before defining,\nand give a library that must coexist with others a scoped registry of its own.\n\n**Closed mode is treated as protection.** Closed mode hides the root from the\nhost's `shadowRoot` property and hides internal nodes from an event's composed\npath as seen by listeners outside that closed shadow tree. CSS Shadow Parts\nstates plainly that shadow trees are deliberately not a security boundary, only\na convenience for page authors. Keep secrets out of components, and choose\nclosed mode for its effect on outside code, not as a lock.\n\n**`attachShadow()` is called where it cannot work.** The DOM Standard allows a\nshadow root only on elements with a valid custom element name and on a short\nlist of built-in ones, among them `div`, `section`, `p` and `span`, but not\n`button`. On a customized built-in button, the call throws a\n`NotSupportedError`. It also behaves differently on an element that already has\na root: if that root is declarative and of the same mode, the call removes\neverything in it and returns it empty, and otherwise it throws. Check for an\nexisting shadow root first, so that markup sent from the server in a declarative\nroot is kept rather than wiped.\n\n**Page styles are expected to reach inside.** CSS Shadow Parts calls the\nboundary a styling barrier, and notes that it also makes a component harder to\nstyle when the page wants to. Expose the elements a page may style with `part`,\nand style them from outside with `::part()`. A component nested inside another\nneeds `exportparts` on the inner host to pass its parts on to the page. For\ncolours and spacing that should follow the page, read custom properties set on\nthe host, which reach the shadow tree by inheritance.\n\n**The content exists only after the script.** A component that writes all its\ntext from JavaScript shows readers none of it until the definition has loaded,\nand none at all if the script fails. Keep the content in the light tree and\nassign it to slots, as the product card does, so that upgrading enhances what is\nalready there. Where content must wait, the HTML Standard's own example hides it\nuntil `customElements.whenDefined()` has resolved for every element matching\n`:not(:defined)`.\n\n## Further reading\n\n- [HTML Standard: Custom elements](https://html.spec.whatwg.org/multipage/custom-elements.html)\n  — naming rules, constructor requirements, upgrades, form-associated elements\n  and `ElementInternals`, with worked examples.\n- [DOM Standard: Shadow tree](https://dom.spec.whatwg.org/#shadow-trees)\n  — shadow roots and their hosts, slots and the nodes assigned to them, and the\n  steps behind `attachShadow()`.\n- [HTML Standard: Scripting](https://html.spec.whatwg.org/multipage/scripting.html)\n  — the `template` element with its `shadowrootmode` attribute, and the `slot`\n  element.\n- [CSS Shadow Parts](https://www.w3.org/TR/css-shadow-parts-1/)\n  — the W3C Working Draft of 16 December 2025 that defines `part`, `exportparts`\n  and the `::part()` pseudo-element.\n\n\u003chttps://engineer.company/glossary/web-components/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"How custom elements, shadow trees and the template and slot elements let a team ship its own HTML tags, with a worked example and the traps to avoid.","formats":{"gemtext":"https://engineer.company/glossary/web-components/index.gmi","gopher":"https://engineer.company/glossary/web-components/gophermap","html":"https://engineer.company/glossary/web-components/","json":"https://engineer.company/glossary/web-components/index.json","markdown":"https://engineer.company/glossary/web-components/index.md","pdf":"https://engineer.company/glossary/web-components/index.pdf"},"kind":"page","language":"en","title":"What are web components?","url":"https://engineer.company/glossary/web-components/","version":1}