Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Your First Web Component

Build your first complete Web Component: a counter button with a custom tag, a class, a shadow root, a template and event handling, explained line by line.

In the last lesson you saw a custom element that wrote a sentence. Now you will build something that behaves like a real component: a counter button with its own look, private styles and click handling. You will use all three technologies once, so the rest of the track has a shape to hang on.

The recipe never changes. You write a class that extends HTMLElement, put the component's markup inside it, and register the class under a tag name with customElements.define.

Step 1: the class

A custom element is a JavaScript class that extends HTMLElement. The browser creates one instance per tag in the page.

JavaScript
class ClickCounter extends HTMLElement {
  constructor() {
    super();          // always first
    this.count = 0;
  }
}

Two rules for the constructor: call super() first, and do not read attributes or add children there. At construction time the element may not have its attributes or children yet. Real setup work belongs in lifecycle callbacks, which you will study in the next chapter.

Step 2: attach a shadow root

A shadow root is a private tree attached to your element. Anything you put inside it is hidden from the page's CSS and from document.querySelector.

JavaScript
this.attachShadow({ mode: "open" });

With mode: "open", the shadow root is also reachable as element.shadowRoot, which is handy for debugging. You will compare open and closed modes in chapter 3.

Step 3: render markup and styles

Write the internals with an ordinary string and innerHTML for now. Styles placed inside the shadow root apply only there.

A counter component

The page's button { background: crimson } rule does not touch the buttons inside the components. That is Shadow DOM at work: the rule and the component each live in their own style scope.

Step 4: register the tag

JavaScript
customElements.define("click-counter", ClickCounter);

define takes a name and a class. The name must be lowercase, start with a letter and contain at least one dash. After this call the browser upgrades every existing <click-counter> in the page and handles all future ones, including those you create with document.createElement("click-counter").

You can only define a name once. Calling define again with the same name throws a NotSupportedError, and so does registering the same class under two names.

Step 5: use a template instead of a string

Strings are fine for small components, but a <template> element is parsed once and cloned cheaply. It also keeps your markup out of JavaScript. Here is the same counter written the way most production components do it.

Counter with a template

Three new ideas appear. template.content holds the inert markup, and cloneNode(true) makes a fresh copy for each instance. :host is a selector that targets the component's own tag from inside its shadow root. And <slot> marks the place where the text written between the tags (Taps, Likes) appears. Each idea has its own chapter later.

Notice that the constructor attaches the shadow root and builds the content here. That is allowed because it does not read attributes or children; it only creates a shadow tree. Many components do exactly this.

The shape of every component

flowchart LR
  A["class extends HTMLElement"] --> B["constructor: attachShadow"]
  B --> C["render: template or innerHTML"]
  C --> D["customElements.define(name, class)"]
  D --> E["use the tag in HTML"]

The same five steps apply to every Web Component you will write.

Common beginner mistakes

  • No dash in the name. define("counter", ...) throws a SyntaxError.
  • Forgetting super(). The constructor throws a ReferenceError.
  • Using document.querySelector to find inner parts. The shadow tree is private; use this.shadowRoot.querySelector.
  • Defining before the class exists. Class declarations are not hoisted like functions, so call define after the class.
  • Self-closing tags. <click-counter /> does not close the element in HTML. Always write the closing tag.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call registers a custom element?

    customElements.define takes the tag name and the class and registers it with the browser.
  2. 2. Why does a page rule like button { background: crimson } not affect buttons inside a shadow root?

    Selectors in the document do not cross the shadow boundary, so the internals keep their own styling.
  3. 3. What must be the very first statement in a custom element constructor?

    A derived class must call super() before it can use this.
  4. 4. How do you get a fresh copy of a template's contents for each instance?

    template.content is a DocumentFragment, and cloning it with true copies the whole subtree.

Summary

  • A component is a class extending HTMLElement registered with customElements.define(name, Class).
  • Names need a dash, and each name or class can be registered only once.
  • attachShadow({ mode: "open" }) creates a private tree with scoped CSS.
  • Render with innerHTML for quick work or clone a <template> for reuse.
  • Use :host to style the component's own tag and <slot> to accept content.

Next: How the Three Technologies Fit Together