Shadow DOM

👉 Overview


👀 What ?

Shadow DOM is a web standard that allows the encapsulation of CSS and Javascript in a web component. It is a part of the larger Web Components standard, which also includes HTML Templates, Custom Elements, and HTML Imports.

🧐 Why ?

Shadow DOM tackles the global nature of HTML, CSS, and Javascript. Without it, styles can leak into components, scripts can unintentionally affect the whole document, and the structure of your HTML can be difficult to manage. Shadow DOM provides a way to bundle CSS and Javascript with markup structure. This encapsulation allows a defined subset of HTML to be packaged and reused, keeping implementation details separate from the rest of the document and preventing accidental interaction with outside styles or scripts.

⛏️ How ?

Creating a shadow DOM starts with attaching a shadow root to an element using the 'attachShadow()' method. Once a shadow root is attached to an element, you can append elements to the shadow root instead of the original element. The elements appended to the shadow root form a separate DOM tree and won't interact with the main document's DOM. This tree is rendered separately from the main document's DOM, providing style and behavior encapsulation.

⏳ When ?

The concept of Shadow DOM was first introduced as a part of the Web Components standard by W3C around 2011. It was adopted by Chrome in 2014, and later by other major browsers.

⚙️ Technical Explanations


Shadow DOM works by creating a separate DOM tree, the shadow tree, attached to an element on the original DOM tree, known as the shadow host. The shadow tree is rendered separately from the main document's DOM, ensuring style and behavior encapsulation. It is accessible via JavaScript but remains separate from the main document's DOM, providing a secure way to encapsulate the implementation details of a web component.

We use cookies

We use cookies to ensure you get the best experience on our website. For more information on how we use cookies, please see our cookie policy.