Custom elements

Custom elements let you create reusable HTML components with your own tag names. JavaScript can define their behavior while the markup remains part of the document.

What you will learn

Basic example

<user-badge name="Ada"></user-badge>
<script>
  class UserBadge extends HTMLElement {
    connectedCallback() {
      this.textContent = `User: ${this.getAttribute('name')}`;
    }
  }
  customElements.define('user-badge', UserBadge);
</script>

A custom element name must contain a hyphen, such as user-badge. Define it once, then use the tag wherever the component is needed.

Prefer native elements for meaning

Custom elements do not automatically behave like buttons, links, headings, or form controls. Use a native element when it already represents the needed meaning. If a custom component needs interaction, add an appropriate semantic element, keyboard behavior, focus handling, and accessible name.

Plan for loading and fallback

The browser can parse an unknown custom tag before its definition loads, but it will not have the intended behavior yet. Keep important content understandable before JavaScript runs, and consider how the component behaves if the script fails.

Related pages