Skip to main content
Practice Problems

What is shadow DOM in web development

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.


Why Shadow DOM?

Encapsulation

Everything inside Shadow DOM is not directly accessible from outside: neither CSS styles nor JS code from outside affect component internals.

Style isolation

Styles written in Shadow DOM don't leak outside, and vice versa — external styles don't affect internal structure of component.

Component purity

Shadow DOM makes Web Components more reliable and independent from external environment.


How to Use Shadow DOM

Created via .attachShadow() method:

html
<div id="my-element"></div> <script> const host = document.getElementById("my-element"); const shadow = host.attachShadow({ mode: "open" }); shadow.innerHTML = ` <style> p { color: red; } </style> <p>Hello from Shadow DOM!</p> `; </script>
  • mode: "open" — allows accessing shadowRoot from outside via JS.
  • mode: "closed" — makes shadowRoot completely private.

Structure

DOM

Custom Element

Shadow Root

Shadow DOM Tree

Light DOM (fallback content)

  • Custom Element — custom HTML tag (e.g., <my-modal>).
  • Shadow Root — root of isolated tree.
  • Shadow DOM Tree — component content (internal HTML + styles).
  • Light DOM — content passed inside tag as regular children.

Web Component Example

js
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:

html
<my-element></my-element>

Component will render, but its styles won't conflict with external ones.

When to Use Shadow DOM?

Suitable for:

  • Web Components (e.g., <my-button>, <user-card>)
  • UI libraries with own styles (without conflicts)
  • Encapsulating logic and markup

Not required if:

  • You work within frameworks (React, Vue) that solve isolation differently
  • Components don't require strict isolation from external CSS

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.

Content

Why Shadow DOM?How to Use Shadow DOMStructureWeb Component ExampleWhen to Use Shadow DOM?

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems