Defining Custom HTML Elements

window.customElements is the page's CustomElementRegistry. define(name, class) registers a hyphenated tag whose class extends HTMLElement, get(name) returns the class or undefined, and whenDefined(name) returns a promise that resolves when the tag is registered. Elements already in the page are upgraded when their definition arrives. Lifecycle callbacks and shadow DOM are covered in Custom Elements.

Registering a custom element and waiting for itHTMLLive
<my-animal>Lucky</my-animal> is a nice dog. <span id="out"></span>
<script>
  customElements.whenDefined('my-animal')
    .then((cls) => { document.querySelector('#out').textContent = `(${cls.name} is defined)`; });
  customElements.define('my-animal', class MyAnimal extends HTMLElement {
    connectedCallback() { this.style.cssText = 'color: brown; background: yellow'; }
  });
</script>
Browser output of Listing 8.6
Browser output of 6