A custom element can use connectedCallback() to set itself up when it is connected to the DOM. The browser calls this lifecycle method automatically. Typical setup includes adding DOM content or event listeners; it can also include opting into shadow DOM. section 3.2
Set up a radio group
A <radio-group> can take labels, values, a name, and a selected value from its attributes. In connectedCallback(), it reads those attributes, checks that name is present, renders its radio buttons, then sets the selected value. This lets markup supply the inputs while the component creates the controls. section 3.10
Listing 3.18 connectedCallback method
connectedCallback() {
this.labels = this.getAttribute("labels");
this.legend = this.getAttribute("legend");
this.name = this.getAttribute("name");
this.values = this.getAttribute("values");
this.#valueArray = this.values.split(",").map((value) => value.trim());
if (!this.name) throw new Error("name is a required attribute");
this.render();
this.value = this.getAttribute("value"); #1
this.#connected = true;
}
See the order of operations: read attributes, prepare the values, render, set the selected value, and mark the component as connected. section 3.10
Connection setup and later updates need not do the same work. In this radio group, attributeChangedCallback() can receive initial attribute assignments; a connected flag prevents a full re-render for each one. After rendering, changing value uses a setter to update the selected radio button instead of replacing the whole shadow DOM. section 3.10
Another radio-group implementation reads attributes and renders in connectedCallback(), then attaches a change listener to each generated input. If connection-time setup adds resources that need cleanup, disconnectedCallback() is the corresponding place to remove listeners or stop timers when the element leaves the DOM. section 9.1 section 3.2


