Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Custom Elements

Autonomous Custom Elements

Learn how to define autonomous custom elements: valid names, the HTMLElement class, constructor rules, display behavior, the registry API and common pitfalls.

There are two kinds of custom elements. Autonomous custom elements, the subject of this lesson, are brand-new tags such as <user-card> that extend the generic HTMLElement. Customized built-in elements extend an existing element such as <button>; they come later in this chapter. Autonomous elements are the default choice and work in every browser.

Valid names

The browser is strict about names, because it must tell custom elements apart from the elements that HTML already has, now and in the future. A valid name:

  • is all lowercase and starts with a letter,
  • contains at least one hyphen,
  • may contain digits, hyphens, underscores and periods after the first letter,
  • is not one of the reserved hyphenated names that already exist in SVG and MathML, such as font-face, annotation-xml or color-profile.
Name Valid?
user-card Yes
x-tab-panel Yes
my_widget-2 Yes
card No, no hyphen
UserCard No, uppercase letters
font-face No, reserved

You can ask the browser directly. The registry throws if a name is invalid, so a tiny helper makes the rules easy to explore.

JS Which names are valid?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Valid names print valid; invalid ones print SyntaxError. Because each valid name is registered by the check, the same name cannot be reused in the same run.

The class

An autonomous element is a class that extends HTMLElement:

JavaScript
class UserCard extends HTMLElement {
  constructor() {
    super();
  }
}
customElements.define("user-card", UserCard);

Because it extends HTMLElement, your element automatically has everything a normal element has: id, className, style, classList, addEventListener, querySelector, hidden, tabIndex, dataset and the rest. You add your own properties and methods on top.

Rules for the constructor

The constructor runs when the element is created, either by the parser or by document.createElement. The specification limits what it may do:

  1. Call super() first, with no arguments.
  2. Do not return a value.
  3. Do not read or write attributes or children of the element. If the element is created by createElement, it must be empty; if it is created by the parser, it may not have its attributes yet.
  4. Do not inspect the parent or siblings.

Safe work in the constructor: initialize fields, attach a shadow root, set up event handlers on the shadow tree. Everything else goes into connectedCallback, covered in the next lesson.

Default display

Unknown and custom elements are display: inline by default, like <span>. Most components want to be a block or inline-block, so set it in CSS:

CSS
user-card { display: block; }

Inside Shadow DOM, set it with :host:

CSS
:host { display: block; }

Forgetting this causes the classic bug where width, height and margins seem to be ignored.

Light DOM children

Whatever you write between the tags is the element's light DOM. An autonomous element can use that content, transform it or ignore it.

Using the element's content

Here the component reads its children in connectedCallback, which is allowed because the element is already in the page.

Creating elements from script

An element defined with customElements.define can be created in four ways, and all four give you an instance of your class:

JavaScript
const a = document.createElement("user-card");
const b = new UserCard();
const c = document.querySelector("user-card");
const d = document.importNode(someTemplateContent, true).firstElementChild;

new UserCard() works only after the element is defined, and the instance is not in the page until you append it.

Creating components from script

The registry API

customElements is a CustomElementRegistry with a few methods:

Method Purpose
define(name, Class, options?) Register a class under a name
get(name) Return the class for a name, or undefined
getName(Class) Return the registered name for a class, or null
whenDefined(name) Promise that resolves when the name is defined
upgrade(root) Upgrade elements in a subtree that already exist

You will use whenDefined and upgrade in the lesson on upgrading.

Pitfalls to remember

  • A tag cannot be self-closing: <user-card /> leaves the element open and swallows the following siblings.
  • Adding attributes or children in the constructor makes document.createElement("user-card") fail.
  • Every class and every name can be registered only once.
  • Custom elements are display: inline until you change it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is a valid custom element name?

    Names need a hyphen and must be lowercase, and font-face is reserved.
  2. 2. What is the default display value of an autonomous custom element?

    Unknown and custom elements are inline by default, so set display yourself when you want a block.
  3. 3. Which action is NOT allowed in a custom element constructor?

    Elements created with createElement must be empty, so setting attributes or children in the constructor breaks them.
  4. 4. What does customElements.get('x-y') return for an unregistered name?

    get returns the class if the name is registered and undefined otherwise.

Summary

  • Autonomous custom elements are new tags whose class extends HTMLElement.
  • Names are lowercase and need a hyphen; reserved SVG/MathML names are not allowed.
  • Keep the constructor minimal: super(), fields and a shadow root only.
  • Set display yourself, because custom elements start as inline.
  • The registry offers define, get, getName, whenDefined and upgrade.

Next: Custom Element Lifecycle Callbacks