typestar

A custom element in JavaScript

Your own tag, with shadow DOM and lifecycle callbacks.

class StarRating extends HTMLElement {
  static observedAttributes = ["stars"];

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

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback(name, previous, next) {
    if (previous !== next) this.render();
  }

  render() {
    const stars = Number(this.getAttribute("stars") ?? 0);
    this.shadowRoot.innerHTML = `
      <style>:host { color: rebeccapurple; }</style>
      <span>${"*".repeat(stars)}${".".repeat(3 - stars)}</span>
    `;
  }
}

customElements.define("star-rating", StarRating);

How it works

  1. connectedCallback runs when it enters the document.
  2. observedAttributes drives attributeChangedCallback.
  3. Shadow DOM scopes the styles to the component.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
532
Tokens
125
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 2 of 2 in Watching & drawing, step 10 of 13 in The browser.

← Previous Next →

A custom element in other languages