Open In App

What is shadow root and how to use it ?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A shadow root is the root node of a shadow DOM, which is a hidden DOM subtree attached to an element in the main DOM. This allows for the encapsulation of HTML, CSS, and JavaScript, enabling the creation of self-contained components.

  • Encapsulation: Isolates component styles and behavior from the global document, preventing unintended interactions.
  • Reusability: Facilitates the development of modular components that can be reused across different parts of an application.
  • Maintainability: Simplifies code management by keeping component-specific code separate from the main document.

Prerequisites for Understanding Shadow DOM

Before diving into Shadow DOM, it’s essential to have a solid understanding of the basics of the DOM, DOM tree, and Web Components. Check out these helpful resources:

Shadow DOM in Web Components

The Shadow DOM is a key feature of Web Components that enables developers to encapsulate a component's internal structure and styling. This ensures that styles and scripts do not leak out or get affected by the rest of the page.

Key Concepts of Shadow DOM

  • Shadow Host: The element to which the shadow DOM is attached.
  • Shadow Tree: The DOM tree inside the shadow DOM.
  • Shadow Boundary: The boundary between the main DOM and shadow DOM.
  • Shadow Root: The root node of the shadow tree.
HTML DOM

Creating a Shadow DOM:

To create a shadow DOM, you can use the attachShadow() method on a DOM element. This method takes an object with a single property, mode, which can be set to either 'open' or 'closed'. An open Shadow Root can be accessed using JavaScript, while a closed one cannot.

HTML
<!--Driver Code Starts-->
<div id="shadow-host"></div>

<!--Driver Code Ends-->

<script>
  const shadowHost = document.getElementById('shadow-host');
  const shadowRoot = shadowHost.attachShadow({ mode: 'open' });

  const paragraph = document.createElement('p');
  paragraph.textContent = 'This is inside the shadow DOM';
  shadowRoot.appendChild(paragraph);
</script>


In this example:

  • A shadow root is attached to the <div> with the ID shadow-host.
  • A <p> element is created and its text content is set.
  • The paragraph is appended to the shadow root, encapsulating it within the shadow DOM.

Best Practices for Using Shadow DOM

  • Encapsulate Styles Within the Shadow DOM: Always define component-specific styles within the shadow root to avoid relying on global styles.
  • Use the mode Property Wisely: When attaching a shadow root, choose between 'open' and 'closed' modes based on your need for external access. An open shadow root can be accessed via JavaScript, while a closed one cannot.
  • Leverage Slots for Content Distribution: Utilize <slot> elements to allow users to insert content into your component, enhancing its flexibility and reusability.

Next Article

Similar Reads