A constructor is a special class method that creates and initializes an object instance. In a custom element, it runs before the element is attached to the DOM, so surrounding attributes, parents, siblings, and other DOM context may not yet be available. section 3.11
Attach a shadow root once
A custom-element constructor is a good place to attach its shadow DOM immediately: constructor() { super(); this.attachShadow({ mode: "open" }); } The constructor runs once for each instance, making it suitable for one-time setup. Open mode exposes shadowRoot for easier debugging and testing; closed mode is rarely useful because it complicates integration. section 4.2.2
Use constructor timing to separate one-time setup from DOM-dependent rendering:
- Perform instance initialization and attach the shadow root in the constructor when the operation should happen once. section 4.2.2
- Avoid querying parent elements, siblings, or surrounding attributes there, because the element may not yet be attached. section 3.11
- Use connectedCallback for work that should occur whenever the element is inserted, including rendering that depends on available DOM context. section 3.11
- Remember that attributeChangedCallback can run before connectedCallback, so attribute-driven rendering must tolerate that order. section 3.1.2
Populating all rendered DOM in the constructor may work, but it is often the wrong lifecycle choice. Detached and reattached elements receive connectedCallback again, while their constructor does not run again; rendering logic must account for that difference. section 3.11 section 4.2.2
constructor() {
super();
this.attachShadow({ mode: "open" });
}
Inspect the compact constructor pattern for calling the superclass and attaching an open shadow root. section 4.2.2

















