Course contentsShow
← Web Development
Lesson 2461 of 2,98244. Web ComponentsFree lesson

Creating a Shadow Root

Using attachShadow() to create a shadow root with open or closed mode on a custom element.

Creating a Shadow Root

You'll learn: How to attach a shadow root to a custom element using attachShadow() and understand the difference between open and closed modes.

What Is a Shadow Root?

A shadow root is the entry point to a shadow DOM tree. Think of it as planting a tree in your garden—the shadow root is where the tree connects to the ground, and everything that grows from it (the shadow DOM) exists in its own protected space.

Using attachShadow()

To create a shadow root, call the attachShadow() method on any valid HTML element (typically inside your custom element's constructor or connectedCallback):

class MyComponent extends HTMLElement {
  constructor() {
    super();
    // Create a shadow root in 'open' mode
    this.attachShadow({ mode: 'open' });
  }
}

customElements.define('my-component', MyComponent);

Open vs Closed Mode

The mode option determines accessibility:

  • open: The shadow root is accessible via element.shadowRoot from outside JavaScript. This is the most common choice and enables debugging and testing.

  • closed: The shadow root is not accessible externally. Calling element.shadowRoot returns null. This provides stricter encapsulation but makes debugging harder.

// Open mode - external access allowed
const openEl = document.createElement('div');
openEl.attachShadow({ mode: 'open' });
console.log(openEl.shadowRoot); // Returns ShadowRoot object

// Closed mode - external access blocked
const closedEl = document.createElement('div');
closedEl.attachShadow({ mode: 'closed' });
console.log(closedEl.shadowRoot); // Returns null

Most developers use open mode unless they have specific security or encapsulation requirements.

Key Takeaway: attachShadow({ mode: 'open' }) creates a shadow root that serves as the foundation for your shadow DOM tree, with open mode allowing external access and closed mode preventing it.