liveBook · Manning

customElements.get

As explained in Web Components in Action

customElements.get is a browser API method that returns the class constructor registered for a custom element name, or undefined when none is registered.

customElements.get('name') checks the browser’s custom-element registry and returns the class constructor associated with that tag. If no class is registered, it returns undefined. This makes it a small but useful guard before calling customElements.define, which throws when the same name is registered twice. section 2.3 section 14.2

if (!customElements.get('my-custom-tag')) {
   customElements.define('my-custom-tag', class extends HTMLElement {});
}

Guard a custom-element definition so repeated loading or importing does not register the same tag twice. section 2.3

Avoiding a duplicate definition

if (!customElements.get('my-custom-tag')) { customElements.define('my-custom-tag', class extends HTMLElement {}); } The condition is true only when the registry has no constructor for the name, so the definition runs once. This pattern is especially useful when component code may be loaded from more than one place. section 2.3

How Web Components in Action covers it

How deep it goes
Explains the return values and demonstrates a conditional registration pattern, without descending into registry internals.
Examples
Uses a repeated customElements.define call and a guarded my-custom-tag registration.
What it assumes
Assumes familiarity with custom element names and customElements.define while establishing undefined as the unregistered result.
What you can do after
Apply the browser Custom Element API to detect registration before defining a custom element.
How it connects
Ties customElements.get to customElements.define, customElements.whenDefined, custom elements, and HTMLElement.

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.