Custom Element Constructor Restrictions
What you'll learn: The strict rules governing what you can and cannot do inside a custom element's constructor.
When building custom elements, you might assume the constructor works like any other JavaScript class constructor—but Web Components impose special restrictions to ensure predictable, safe behavior.
Why These Restrictions Exist
Custom elements are managed by the browser's parser and DOM engine. The constructor runs at unpredictable moments during parsing, and allowing certain operations would create race conditions or break the rendering pipeline.
The Four Key Restrictions
1. No attributes: You cannot read or set attributes in the constructor. The element's attributes aren't reliably available yet.
2. No children: You cannot access or manipulate childNodes or children. The element hasn't been fully parsed and attached to the tree.
3. No document.write: You cannot call document.write() as it would interfere with the parsing process.
4. Mandatory super() call: You must call super() as the very first statement. This initializes the underlying HTMLElement infrastructure before your custom logic runs.
What You Can Do
You can:
- Set up internal state (properties)
- Create a Shadow DOM (attach shadow root)
- Add event listeners to the element itself
- Initialize default values
Think of the constructor as "setup only"—no I/O, no DOM reading, just preparation. Save meaningful work for connectedCallback, where the element is safely in the document.
Why This Matters
Violating these rules causes browser errors or unpredictable behavior. The constructor is called when the browser creates the element instance, but that doesn't mean it's ready to be used yet.
Key Takeaway: Custom element constructors must call super() first and cannot touch attributes, children, or use document.write—save DOM interaction for lifecycle callbacks instead.