Sub topic 2
Custom elements: defining your own HTML tags
This chapter assumes you know HTML, JavaScript classes, and how to query the DOM and attach event listeners. It also assumes you know that shadow DOM exists. The previous chapter introduced it, and the next one covers it in detail.
A custom element is an HTML tag that you define yourself. You write a JavaScript class, register it under a tag name, and the browser creates instances of that class wherever the tag appears. Every Lightning Web Component is a custom element, so this chapter explains the layer that LWC sits on.
Registering an element
Registration takes two steps. You write a class that extends HTMLElement, then you pass it to customElements.define together with a tag name.
class HelloGreeting extends HTMLElement {
static observedAttributes = ['name'];
constructor() {
super();
this.root = this.attachShadow({ mode: 'open' });
this.paragraph = document.createElement('p');
this.root.append(this.paragraph);
}
connectedCallback() {
this.render();
}
attributeChangedCallback(attrName, oldValue, newValue) {
this.render();
}
get name() {
return this.getAttribute('name') ?? 'World';
}
set name(value) {
this.setAttribute('name', value);
}
render() {
this.paragraph.textContent = `Hello, ${this.name}!`;
}
}
customElements.define('hello-greeting', HelloGreeting);To use it, load the script as a module and write the tag in your markup.
<hello-greeting name="Ada"></hello-greeting>
<script type="module" src="hello-greeting.js"></script>This version differs from the short example in the plan in two ways. It calls attachShadow in the constructor, not in connectedCallback. An element can be disconnected and reconnected, for example when you move it with append. connectedCallback then runs again, and a second attachShadow call throws a NotSupportedError. It also sets textContent instead of building HTML from a string. With innerHTML, a name value such as <img src=x onerror=alert(1)> would be parsed as markup.
Naming rules
The tag name must follow these rules:
- It must contain a hyphen, such as
hello-greeting. The HTML standard reserves hyphen-free names for built-in tags, so a hyphen guarantees no future clash. - It must be lowercase and start with a letter.
- It must be unique. Calling
definetwice with the same name, or with the same class under two names, throws an error.
LWC follows the same rules. A bundle in a folder named helloGreeting is used as <c-hello-greeting>. The c is the namespace, and the compiler converts camelCase folder names to hyphenated tag names.
The lifecycle callbacks
The browser calls these methods on your class at defined moments.
| Callback | When it runs |
|---|---|
| `constructor` | The element is created, by the parser or by `document.createElement`. |
| `connectedCallback` | The element is inserted into a document. It can run many times. |
| `disconnectedCallback` | The element is removed from the document. |
| `attributeChangedCallback` | One of the attributes listed in `observedAttributes` is added, changed, or removed. |
| `adoptedCallback` | The element is moved to another document, such as an iframe. |
The diagram shows how an element moves between these states.
What the constructor may do
The constructor runs early, and the element may not have its attributes or children yet. Follow these rules:
- Call
super()first, with no arguments. - Do not read or set attributes, and do not add children to the element itself. The
createElementpath forbids this, and the parser path can lose the work. - Attaching a shadow root and setting up your own internal state is fine.
Put anything that depends on the element's surroundings in connectedCallback. Because that callback can run again, make it safe to repeat. If you add a window listener there, remove it in disconnectedCallback.
Attributes versus properties
An HTML attribute is a string stored on the tag. A JavaScript property is a value on the object. They are separate, and the browser links them only for built-in elements such as input.value. For a custom element you wire them together yourself.
In HelloGreeting, the name setter writes to the attribute. That write triggers attributeChangedCallback, which re-renders. The class has one source of truth, the attribute, and both ways of setting it work:
const el = document.querySelector('hello-greeting');
el.name = 'Grace'; // property, updates the attribute
el.setAttribute('name', 'Alan'); // attribute, read back by the getterKeep two limits in mind. Attributes are always strings, so objects and arrays need a property. And attributeChangedCallback only fires for names listed in observedAttributes.
LWC takes the same split. A parent that writes label="Increase" in a template passes a value to a public property. You do not write observedAttributes in an LWC class. Public properties, covered in a later chapter, serve that purpose.
Upgrading and timing
The browser can parse a tag before your script defines it. The element is then an ordinary HTMLElement with an unknown name. When define runs, the browser upgrades every existing matching element in the document. Their constructors run, then attributeChangedCallback for each observed attribute already present, then connectedCallback.
The upgrade has a visible consequence. If you query an element before its definition has loaded, the element has no custom properties or methods. The browser provides a way to wait:
await customElements.whenDefined('hello-greeting');
const el = document.querySelector('hello-greeting');
el.name = 'Grace';To check whether a name is registered, call customElements.get('hello-greeting'). It returns the class, or undefined.
Autonomous and customized built-in elements
The form shown so far is an autonomous custom element, which extends HTMLElement. The standard also describes customized built-ins. These extend a real element such as HTMLButtonElement, and you use them as <button is="fancy-button">. Safari does not implement them, so most projects avoid them. LWC does not use them either.
How this maps to LWC
The compiler turns each LWC bundle into a class that is registered as a custom element. A few things differ from the plain version above:
- You extend
LightningElement, notHTMLElement. The framework supplies the custom element machinery for you. - You do not call
customElements.defineyourself. The framework and the platform register components. connectedCallbackanddisconnectedCallbackkeep their standard names and meaning. LWC adds hooks such asrenderedCallback, which are not part of the standard. The lifecycle chapter covers them.- The shadow root is created for you, and the template renders into it.
Because an LWC component is an element, everything the browser does with elements applies. You can listen for events on it, query it in tests, and set properties on it from outside.
Exercise
A developer calls this.attachShadow({ mode: 'open' }) inside connectedCallback. The page works until a script moves the element with container.append(el). Then an error appears. Why, and how do you fix it?
Show answer
Moving the element disconnects and reconnects it, so connectedCallback runs a second time. A second attachShadow call on the same element throws a NotSupportedError. Move the attachShadow call into the constructor, which runs once per element, and keep connectedCallback limited to work that is safe to repeat.
Exercise
You add <hello-greeting name="Ada"> to a page, and the script that defines the element loads later. In what order do the constructor, attributeChangedCallback, and connectedCallback run for that tag once define is called?
Show answer
The element is upgraded. The constructor runs first, then attributeChangedCallback for the existing name attribute (because it is in observedAttributes), then connectedCallback.