Skip to content

Shadow DOM

In one line

Shadow DOM attaches a hidden, isolated DOM subtree to an element so its styles and markup do not leak out or in.

In simple words

Shadow DOM lets you attach a separate, encapsulated DOM tree to a regular element. The shadow tree's styles and IDs are scoped — they do not clash with the host document, and the host's styles do not bleed into the shadow tree. This is how built-in elements like <video> or <input type=range> hide their internal sliders and buttons.

You create a shadow root with element.attachShadow({ mode: 'open' or 'closed' }) and then populate it like a normal DOM. The shadow boundary prevents document CSS selectors from matching inside, and prevents IDs inside from being found by document.getElementById. This gives true encapsulation without naming conflicts.

Shadow DOM is a building block of Web Components. Use it when you need a self-contained widget whose internal markup and styles must not interfere with the page — a third-party embed, a complex custom element, or a reusable UI primitive.

Example

javascript
const host = document.createElement("div");
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = `
  <style>p { color: red; }</style>
  <p>Shadow text</p>
`;
document.body.appendChild(host);

// The <p> inside is red, but document <p> tags are unaffected
// document.querySelector("p") does NOT find the shadow <p>

attachShadow creates an isolated subtree. The style inside only affects the shadow <p>, not the host document's paragraphs.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary