Sub topic 2
Custom elements: defining your own HTML tags
This chapter assumes you know HTML, JavaScript classes, and how the browser DOM and event listeners work. Custom elements are the first web standard LWC builds on. Each LWC component becomes a custom element, so this chapter explains the standard before any framework code.
What a custom element is
A custom element is an HTML tag that you define yourself. You write a JavaScript class that extends HTMLElement. You then register the class under a tag name with customElements.define. After registration, the browser creates an instance of your class whenever it finds that tag in the page.
class HelloGreeting extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
const name = this.getAttribute('name') ?? 'World';
root.innerHTML = `<p>Hello, ${name}!</p>`;
}
}
customElements.define('hello-greeting', HelloGreeting);With this script loaded, the markup below renders "Hello, Ada!".
<hello-greeting name="Ada"></hello-greeting>Naming rules
The tag name passed to define must follow these rules:
- It must contain a hyphen, as in
hello-greeting. This keeps custom names from clashing with built-in tags, which never contain one. - It must be lowercase and start with a letter.
- Each name can be registered only once per page. A second
definecall with the same name throws an error.
Callbacks the browser calls
The browser calls certain methods on your class at fixed moments. These are the custom element callbacks.
| Callback | When the browser calls it |
|---|---|
| `constructor` | The element instance is created |
| `connectedCallback` | The element is inserted into a document |
| `disconnectedCallback` | The element is removed from a document |
| `attributeChangedCallback` | An attribute listed in `observedAttributes` changes |
The arrow from removal back to insertion reflects that an element can be moved or re-inserted. connectedCallback can therefore run more than once for the same instance.
Common errors
- Reading attributes in the constructor. The element may not have its attributes yet. Read them in
connectedCallback, as the example does. - Calling
attachShadowtwice. Each element can have only one shadow root. Calling it again throws an error. BecauseconnectedCallbackcan run repeatedly, moveattachShadowto the constructor in real code. - Expecting attribute changes to be noticed automatically. The browser reports changes only for names you return from a static
observedAttributesgetter.
class HelloGreeting extends HTMLElement {
static get observedAttributes() {
return ['name'];
}
attributeChangedCallback(attr, oldValue, newValue) {
console.log(`${attr} changed from ${oldValue} to ${newValue}`);
}
}
customElements.define('hello-greeting', HelloGreeting);How this connects to LWC
An LWC component class extends LightningElement, which itself builds on HTMLElement. The framework registers a custom element for each component. It also calls your lifecycle hooks from the callbacks above. Later chapters cover that mapping in detail.
Exercise
Why does customElements.define('greeting', HelloGreeting) fail, and how do you fix it?
Show answer
Custom element names must contain a hyphen. greeting has none, so the browser rejects it. Use a name such as hello-greeting.
Exercise
A custom element is removed from the page and later appended again. Which callbacks run, and in what order?
Show answer
disconnectedCallback runs on removal. connectedCallback runs when it is appended again. The constructor does not run a second time, because the same instance is reused.