A custom element’s constructor prepares internal state, but its HTML attributes and child nodes may not yet be available. The browser calls connectedCallback() when the element enters a document. Use it for work that needs the element’s DOM, such as reading attributes, rendering content, or registering listeners. section 7.6.1 section 9.2.1
Keep connection work safe to repeat:
- Expect connectedCallback() on every insertion, including reconnection after a move—not just on first creation. section 9.2.1 section 7.7
- Guard one-time DOM creation. Otherwise, reconnecting can duplicate rendered nodes or listeners. section 7.7 section 9.2
- Pair subscriptions made on connection with cleanup in disconnectedCallback(). A later connection can then subscribe again. section 13.2.7
Listing 7.2 A CounterButton web component
class CounterButton extends HTMLElement {
#count; #1
constructor() {
super();
this.#count = 0; #2
}
connectedCallback() {
if (this.querySelector('button')) return; #3
const button = document.createElement('button');
button.textContent = 'Clicks: 0';
button.addEventListener('click', () => {
this.#count++; #4
button.textContent = `Clicks: ${this.#count}`;
});
this.appendChild(button);
}
}
customElements.define('counter-button', CounterButton);
The counter button checks for an existing button before creating its DOM and click listener, so a later connection does not create another button. section 7.7
Creating an element with JavaScript does not run connectedCallback() until it is attached to a document. An observed attribute can also change before connection, so rendering from attributeChangedCallback() may need an isConnected check. Attributes and properties do not synchronize automatically. section 7.6.3 section 9.2.1 section 7.9
class CartSummary extends HTMLElement {
#store;
#unsubscribe;
set store(value) {
this.#store = value;
this.#resubscribe();
}
connectedCallback() {
this.#resubscribe();
}
disconnectedCallback() {
this.#unsubscribe?.();
this.#unsubscribe = undefined; #1
}
#resubscribe() {
this.#unsubscribe?.();
if (!this.#store || !this.isConnected) return;
this.#unsubscribe = this.#store.subscribe((state) => {
this.textContent = `${state.items.length} items`;
});
}
}
customElements.define("cart-summary", CartSummary);
The cart summary subscribes only while connected and clears its unsubscribe function on removal, making reconnection safe. section 13.2.7


