Skip to content
jshacks.dev
Browser

How to Build a Web Component From Scratch

Build a web component from scratch with a custom element class, shadow DOM, attributes, properties, events, slots and lifecycle callbacks, no library needed.

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, webcomponents.org, GraphQL and Postman logos.

Web components are the browser's own way to make reusable elements: you define a new tag, such as <rating-stars>, give it behavior and styles, and use it in any page or framework. They are built from three standards, custom elements, shadow DOM and templates and slots, and every current browser supports them. No library is required, which makes them a good fit for widgets that must live in many places, for design systems shared across teams that use different frameworks, and for questions about how the platform works. This guide shows how to build a web component from scratch: defining a custom element class and registering it, the naming rule, lifecycle callbacks, attributes and properties and how they relate, the shadow root and scoped styles, templates and slots, dispatching events, forms participation in brief, testing and the trade-offs. The standards are documented on MDN and in the HTML Standard.

The smallest custom element

A custom element is a class that extends HTMLElement, registered under a name with customElements.define(). The name must contain a hyphen, so that it can never collide with a future built-in tag.

hello.jsJavaScript
class HelloCard extends HTMLElement {
  connectedCallback() {
    this.textContent = "Hello from a custom element";
  }
}

customElements.define("hello-card", HelloCard);

document.body.append(document.createElement("hello-card"));
console.log(document.querySelector("hello-card").textContent);
Text
Hello from a custom element

From now on, <hello-card></hello-card> in HTML or document.createElement("hello-card") in script produces an instance of the class. connectedCallback() runs when the element is inserted into the document. Registering an already defined name throws, so definitions normally live in one module that is imported once.

Lifecycle callbacks

The browser calls a small set of methods at defined moments. constructor() runs when the element is created, and should set up internal state but not touch attributes or children, because they may not exist yet. connectedCallback() runs each time the element is added to a document, which is where you render and add listeners. disconnectedCallback() runs when it is removed, which is where you clean up. attributeChangedCallback(name, oldValue, newValue) runs when an observed attribute changes. adoptedCallback() runs when the element moves to another document.

lifecycle.jsJavaScript
class LifeCycle extends HTMLElement {
  static observedAttributes = ["label"];

  constructor() {
    super();
    console.log("constructor");
  }

  connectedCallback() {
    console.log("connected");
  }

  disconnectedCallback() {
    console.log("disconnected");
  }

  attributeChangedCallback(name, oldValue, newValue) {
    console.log("attribute", name, oldValue, "->", newValue);
  }
}

customElements.define("life-cycle", LifeCycle);

const el = document.createElement("life-cycle");
el.setAttribute("label", "A");
document.body.append(el);
el.remove();
Text
constructor
attribute label null -> A
connected
disconnected

Only attributes listed in the static observedAttributes array trigger the callback. Notice the order when the element is created from script: the constructor, then the attribute change and then the connection. When the browser parses markup that already has attributes, the attribute callbacks run before connectedCallback() as well, so write connectedCallback() to be safe to call more than once, since moving the element calls it again.

Shadow DOM for encapsulation

A shadow root gives the element its own DOM tree and style scope. Styles written inside do not leak out, and page styles do not reach in, so the component looks the same everywhere. Attach it in the constructor with attachShadow({ mode: "open" }), where open lets outside script reach element.shadowRoot.

shadow.jsJavaScript
class RatingStars extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
  }

  connectedCallback() {
    this.render();
  }

  render() {
    const value = Number(this.getAttribute("value") ?? 0);
    this.shadowRoot.innerHTML = `
      <style>
        :host { display: inline-block; font-size: 1.5rem; color: #d4a017; }
        .off { color: #cccccc; }
      </style>
      <span role="img" aria-label="${value} out of 5 stars">
        ${"★".repeat(value)}<span class="off">${"★".repeat(5 - value)}</span>
      </span>`;
  }
}

customElements.define("rating-stars", RatingStars);

document.body.innerHTML = '<rating-stars value="3"></rating-stars>';
console.log(document.querySelector("rating-stars").shadowRoot.querySelectorAll("span").length);
Text
2

The :host selector styles the element itself from inside. Because the markup is built from a template string that includes a value, make sure the value is a number, as the code does; interpolating untrusted text into innerHTML is the same injection risk as anywhere else. For anything dynamic and text-based, create nodes and set textContent.

Attributes and properties

HTML attributes are strings, and script prefers typed properties. A well behaved component offers both and keeps them in sync, by reflecting a property to its attribute and reacting to attribute changes.

props.jsJavaScript
class RatingStars extends HTMLElement {
  static observedAttributes = ["value"];

  get value() {
    return Number(this.getAttribute("value") ?? 0);
  }

  set value(next) {
    this.setAttribute("value", String(next));
  }

  attributeChangedCallback() {
    if (this.isConnected) this.render();
  }

  connectedCallback() {
    this.render();
  }

  render() {
    this.textContent = "★".repeat(this.value);
  }
}

customElements.define("rating-stars", RatingStars);

const stars = document.createElement("rating-stars");
stars.value = 4;
document.body.append(stars);
console.log(stars.getAttribute("value"), stars.textContent);
Text
4 ★★★★

Setting the property writes the attribute, which triggers attributeChangedCallback() and a re-render. This round trip means that CSS attribute selectors, setAttribute and the property all agree. Use attributes for simple, serializable values and properties for objects and arrays, which cannot be put into an attribute sensibly.

Templates and slots

Building markup in strings is fine for small components. A <template> element holds inert markup that you clone, and a <slot> marks where the content that the page author puts between the tags appears. This lets users compose your component with their own content.

slot.jsJavaScript
const template = document.createElement("template");
template.innerHTML = `
  <style>
    :host { display: block; border: 1px solid #ccc; border-radius: 8px; padding: 1rem; }
    h2 { margin: 0 0 0.5rem; font-size: 1.1rem; }
  </style>
  <h2><slot name="title">Untitled</slot></h2>
  <div><slot></slot></div>
`;

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

customElements.define("info-card", InfoCard);

document.body.innerHTML = `
  <info-card>
    <span slot="title">Shipping</span>
    <p>Orders ship within two days.</p>
  </info-card>`;

console.log(document.querySelector("info-card").shadowRoot.querySelectorAll("slot").length);
Text
2

The slot="title" element goes into the named slot, and everything else goes into the default one. The slotted content stays in the page's own DOM, which means the page's CSS styles it and search engines and assistive technology can read it, while the component controls where it is shown. The default text inside a slot shows when nothing is provided.

Events

A component talks to the page by dispatching events, which the page listens to with ordinary addEventListener. Create a CustomEvent, set bubbles and composed so that it crosses the shadow boundary and puts data in detail.

events.jsJavaScript
class StarInput extends HTMLElement {
  connectedCallback() {
    this.addEventListener("click", this.#onClick);
  }

  disconnectedCallback() {
    this.removeEventListener("click", this.#onClick);
  }

  #onClick = () => {
    this.dispatchEvent(
      new CustomEvent("rating-change", {
        detail: { value: 5 },
        bubbles: true,
        composed: true,
      }),
    );
  };
}

customElements.define("star-input", StarInput);

const el = document.createElement("star-input");
document.body.append(el);
document.addEventListener("rating-change", (event) => console.log("rated", event.detail.value));
el.click();
Text
rated 5

Without composed: true an event dispatched from inside a shadow tree does not leave it. Name events in lower case with hyphens and describe what happened, not what to do. Remove listeners in disconnectedCallback(), which pairs with the connectedCallback() that added them.

Styling from outside

The shadow boundary blocks page selectors, which is the goal, but components still need to be themeable. CSS custom properties pass through the boundary, so the component reads variables with defaults, and the page sets them. The ::part() pseudo-element exposes chosen internal elements, marked with the part attribute, to outside styling.

theme.cssCSS
rating-stars {
  --star-color: tomato;
}

info-card::part(title) {
  text-transform: uppercase;
}
Text
(the page tweaks the component without reaching into its internals)

Inside the component, write color: var(--star-color, #d4a017) to give the variable a default. Think of the variables and parts as the public styling API and document them.

Accessibility

A custom element has no built-in semantics. A clickable <my-button> is not focusable, not announced as a button and not activated by the keyboard unless you add it: give it role="button", tabindex="0" and key handlers for Enter and Space, or better, wrap a real <button> inside the shadow root. Reflect state with ARIA attributes such as aria-pressed and aria-expanded, keep focus visible and test with a screen reader. For form controls, the ElementInternals interface, obtained with attachInternals(), lets a custom element take part in forms, validation and labels, with static formAssociated = true.

Testing and tooling

Test components in a real browser, with a test runner that can drive one, because the behavior depends on the platform. Create the element, set attributes, append it, query inside shadowRoot, dispatch events and assert on the result. Wait for rendering to finish if you batch updates. Provide a type declaration or documentation of your attributes, events, slots, parts and variables, since consumers cannot read them from the tag name.

When to use a library

A raw component needs manual re-rendering, event wiring and update batching, which grows tedious for complex views. Small libraries such as Lit add reactive properties, efficient templates and declarative event binding on top of the same standards, in a few kilobytes, and produce standard custom elements. Use plain classes for small, stable widgets and a library when templates and state grow.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.