Open vs Closed Shadow DOM
What you'll learn: How to choose between open and closed shadow roots based on your component's encapsulation needs.
When you create a shadow root, you must specify a mode: either 'open' or 'closed'. This decision affects whether external JavaScript can access your component's shadow DOM internals.
Understanding the Modes
Open Mode creates a shadow root that remains accessible via the element's shadowRoot property. Anyone with a reference to your custom element can read and manipulate its shadow DOM:
const element = document.querySelector('my-component');
console.log(element.shadowRoot); // Returns the shadow root
element.shadowRoot.querySelector('.internal'); // Can access internals
Closed Mode prevents external access by making the shadowRoot property return null. The shadow root reference exists only inside your component's constructor or when initially created:
class MyComponent extends HTMLElement {
constructor() {
super();
// Store reference privately if you need it
this._shadow = this.attachShadow({ mode: 'closed' });
}
}
// Later...
const element = document.querySelector('my-component');
console.log(element.shadowRoot); // null - no external access
When to Use Each
Use open mode (default choice) when:
- You want flexibility for testing, debugging, or legitimate third-party extensions
- There's no security risk in exposing internals (most cases)
- You value openness over strict encapsulation
Use closed mode when:
- You need guaranteed internal implementation privacy
- You're building a security-sensitive component
- You want to prevent accidental external dependencies on internals
Think of it like a house: open mode is a house where visitors can peek through windows (helpful for friends), while closed mode has blackout curtains (more private, but harder for even you to debug later).
Key Takeaway: Open shadow DOM is the recommended default for most components because it maintains encapsulation while allowing developer tools and testing access; use closed mode only when you genuinely need implementation secrecy.