Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 156 ยท The DOM

Custom Elements and Shadow DOM

Build your own HTML tags with custom elements, hide their markup and styles inside shadow DOM, add slots for content and react to lifecycle callbacks.

HTML comes with a fixed set of tags, but you are not limited to them. Custom elements let you define your own tags, such as <user-badge> or <star-rating>, backed by a JavaScript class. Shadow DOM lets such an element keep its inner markup and styles private, so the page's CSS cannot accidentally break it and its CSS cannot leak out. Together with HTML <template>, these browser features are called Web Components, and they work in every modern browser with no library at all.

Why bother? Imagine a "like" button used on fifty pages. Without components you copy the HTML, the CSS and the script around, and fix bugs fifty times. With a custom element, you write <like-button count="12"></like-button> and everything else lives in one class. This lesson shows how to define elements, how shadow DOM isolates them, how slots let users pass content in, and which lifecycle callbacks the browser calls. You should be comfortable with classes, selecting elements and events.

Defining a custom element

A custom element is a class that extends HTMLElement, registered with customElements.define(). Two rules apply:

  1. The tag name must contain a hyphen (user-badge, not badge). That guarantees it can never collide with a future built-in tag.
  2. You must register the class before the browser can upgrade the tags in the page to it. Tags that appear before the definition are upgraded as soon as define() runs.
Your first custom element

Both tags became blue pills, and the console printed one line each. The browser created an instance of UserBadge for every <user-badge> and called connectedCallback() when it was added to the page. Because the element is an HTMLElement, it already has style, classList, addEventListener() and everything else you know from the DOM.

Lifecycle callbacks

The browser calls specific methods on your class at key moments:

Callback When it runs
constructor() The element is created (by the parser or by document.createElement). Keep it light: call super(), set up internal state, but do not read attributes or add children.
connectedCallback() The element is inserted into a document. Can run more than once if the element is moved. This is the place to render and add listeners.
disconnectedCallback() The element is removed. Clean up timers and global listeners here.
attributeChangedCallback(name, oldValue, newValue) An attribute listed in static observedAttributes is added, changed or removed.
adoptedCallback() The element is moved to another document (rare).
stateDiagram-v2
  [*] --> Created: constructor
  Created --> Connected: connectedCallback
  Connected --> Disconnected: disconnectedCallback
  Disconnected --> Connected: inserted again
  Connected --> Connected: attributeChangedCallback
  Disconnected --> [*]

An element can be connected and disconnected many times; attribute changes arrive while it lives in the page.

You must list attributes in observedAttributes for the browser to notify you. Here is a counter that reacts to its count attribute and cleans up after itself:

Observed attributes and cleanup

Notice the property/attribute pair. The count property reads and writes the count attribute, so setting either one triggers attributeChangedCallback. That mirrors how built-in elements work (input.value, a.href), and it lets people use your element from HTML and from JavaScript.

On the first page load, attributeChangedCallback is called for each observed attribute that is already present, before connectedCallback. That is why render() checks isConnected first: an update that arrives before the element is in the page should wait.

Shadow DOM: private markup and styles

Normally every element on a page shares one global stylesheet scope. A stray button { background: red } rule hits every button, including the ones inside your widget. Shadow DOM fixes that by giving an element a hidden subtree, the shadow root, with its own style scope.

You create one with this.attachShadow({ mode: "open" }). In open mode, outside code can reach it through element.shadowRoot; in closed mode it cannot, but open is the usual choice and easier to debug and test.

Shadow DOM keeps styles in and out

The page's red rule did not touch the green button, and the green button's button:hover rule does not leak to the page. Also look at the console: the page's querySelector("fancy-button button") finds nothing (null), because shadow content is not part of the normal DOM tree. You reach inside only through shadowRoot.

A few facts worth remembering:

  • Selectors inside the shadow <style> use :host to style the element itself (:host { display: block }) and :host(.compact) for variants. Without it, custom elements default to display: inline.
  • Inherited CSS properties (color, font-family, line-height) and CSS custom properties do pass through the shadow boundary. That is how you theme a component: expose --accent and let users set it.
  • Elements with a part="name" attribute can be styled from outside with the ::part(name) selector, an intentional hole in the wall.
  • Events that cross the boundary are retargeted: to outside listeners, event.target is the host element, not the inner button. Use event.composedPath() to see the real path, and note that events marked composed: false do not leave the shadow root at all.

Do you need a shadow root? Not always. A light-DOM element (like user-badge above) is simpler and inherits page styles, which is right for small helpers. Reach for shadow DOM when the widget has its own structure and style that must be protected.

Slots: letting users supply content

A component rarely owns all of its content. A card needs a title and a body from whoever uses it. Slots are placeholders inside the shadow tree where the host's own children are displayed. The children stay in the light DOM (so the page can still style and query them), but they are rendered at the slot.

flowchart TD
  H["host: &lt;info-card&gt;"] --> SR["#shadow-root"]
  SR --> T["slot name=title"]
  SR --> D["default slot"]
  H --> L1["light child: span slot=title"]
  H --> L2["light child: p"]
  L1 -.->|"rendered in"| T
  L2 -.->|"rendered in"| D

Children of the host are matched to slots by their slot attribute; unnamed children go to the default slot.

A card with named and default slots

The first card has no footer, so the empty footer slot shows nothing; and if a title were missing, the text inside <slot name="title"> ("Untitled") would be shown as the fallback. The page's .price rule colors the red price even though that text is displayed inside the shadow tree, because those nodes still live in the light DOM and follow page CSS. You can also style slotted content from inside the shadow root with ::slotted(selector), but only for top-level slotted elements.

Using <template> to avoid rebuilding strings

Building the shadow tree with innerHTML works, but for components used many times it is cleaner to parse the markup once. A <template> element holds inert HTML that you clone for each instance:

JavaScript
const template = document.createElement("template");
template.innerHTML = `<style>:host { display: block }</style><slot></slot>`;

class MyBox extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true));
  }
}

The template is parsed once, and each instance only clones it. Keep any user-supplied data out of these strings; set it with textContent instead (see XSS and safe DOM updates).

Practical advice

  • Do not touch attributes or children in the constructor. When the parser creates the element, they may not exist yet. Use connectedCallback(). Creating the shadow root in the constructor is fine.
  • Make connectedCallback idempotent. An element that is moved is disconnected and connected again, so don't append duplicate content or double-register listeners.
  • Communicate with events. Let a component dispatch new CustomEvent("change", { detail, bubbles: true, composed: true }) and let the page listen. Data flows in through attributes and properties, and out through events.
  • Check customElements.get("tag") before defining if a script might load twice, because defining the same name twice throws an error.
  • Wait for definitions when needed with await customElements.whenDefined("my-tag").

Web Components are a platform feature, so you can mix them with any framework, or use none at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tag name is valid for a custom element?

    Custom element names must be lowercase and contain a hyphen, so they can never clash with built-in HTML tags.
  2. 2. Where should an element usually render its content and add event listeners?

    The constructor may run before attributes and children exist. connectedCallback() runs once the element is in the document.
  3. 3. What must you do for attributeChangedCallback to fire for the 'count' attribute?

    The browser only reports changes to attributes named in observedAttributes.
  4. 4. A page rule button { color: red } is defined. What happens to a button inside an open shadow root?

    Selectors in the main document do not match elements inside a shadow tree, and the shadow tree's own styles don't leak out either.
  5. 5. How does a user of your component supply a custom title to be displayed inside its shadow DOM?

    Children of the host are projected into the matching slot, so the component can place user content inside its own structure.

Summary

  • A custom element is a class extending HTMLElement, registered with customElements.define("my-tag", Class); the name needs a hyphen.
  • Render in connectedCallback(), clean up in disconnectedCallback(), and list attributes in observedAttributes to receive attributeChangedCallback().
  • Mirror attributes with properties so the element works from HTML and from JavaScript.
  • attachShadow({ mode: "open" }) creates a private subtree with its own style scope; use :host, ::part() and CSS custom properties to style across the boundary.
  • Slots (default and named) project the host's children into the shadow tree, with fallback content.
  • Communicate outward with CustomEvent (use composed: true to cross the shadow boundary) and use <template> to reuse markup.

Next: The Browser Object Model - the window, location, history, navigator and screen.