Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Shadow DOM is browser technology that allows creating encapsulated DOM trees inside elements.
It isolates HTML, CSS and JS to avoid conflicts with external page styles and scripts.
Everything inside Shadow DOM is not directly accessible from outside: neither CSS styles nor JS code from outside affect component internals.
Styles written in Shadow DOM don't leak outside, and vice versa — external styles don't affect internal structure of component.
Shadow DOM makes Web Components more reliable and independent from external environment.
Created via .attachShadow() method:
<div id="my-element"></div>
<script>
const host = document.getElementById("my-element");
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = ``;
</script>
mode: "open" — allows accessing shadowRoot from outside via JS.mode: "closed" — makes shadowRoot completely private.<my-modal>).class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>p { color: blue; }</style>
<p>I'm in shadow</p>
`;
}
}
customElements.define('my-element', MyElement);
Now in HTML:
<my-element></my-element>
Component will render, but its styles won't conflict with external ones.
Suitable for:
<my-button>, <user-card>)Not required if:
Conclusion:
Shadow DOM is way to create isolated, safe components with own styles and structure. It's foundation of Web Components and used to achieve encapsulation and UI reuse.