Editor's note (2026): We've updated this 2014 post. The original used
webkitCreateShadowRoot(), an experimental Chrome-only method that has been removed. Shadow DOM is now a web standard supported by all modern browsers throughattachShadow().
Why Shadow DOM?
Most websites combine content from many sources: YouTube videos, social media widgets, ads, and styles loaded from third-party servers. When markup, styles, and scripts from different sources mix, they can clash. A style meant for one widget can accidentally change another.
JavaScript code can be isolated with modules and closures, but HTML and CSS were harder to contain. The old workaround, iframes, is heavy and restrictive. Shadow DOM solves this by letting a component keep its own private markup and styles.
How it works
Shadow DOM attaches a hidden, separate DOM tree to an element. Styles and scripts inside that tree don't leak out, and the page's styles don't leak in. Browsers have used this technique for years in built-in controls like <video>, <audio>, and date pickers.
Key terms
- Shadow host: the regular element the shadow DOM is attached to.
- Shadow root: the root node of the shadow tree.
- Shadow tree: the elements inside the shadow root.
- Shadow boundary: the line between the regular DOM and the shadow DOM. Styles don't cross it unless you allow them to.
See it in your browser
Add an audio player to a page:
<audio controls src="sample.mp3">
Your browser does not support HTML5 audio.
</audio>
In Chrome DevTools, open Settings (the gear icon), and under Elements enable Show user agent shadow DOM. Inspect the audio element, and you'll see the hidden markup that builds the player's controls.
Create your own shadow root
<div id="welcomeMessage">Welcome to My World</div>
<script>
const host = document.querySelector('#welcomeMessage');
const shadowRoot = host.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `
<style>
p { color: teal; font-weight: bold; }
</style>
<p>Hello Shadow DOM World</p>
`;
</script>
The page now displays "Hello Shadow DOM World" instead of the original text, and the teal style applies only inside the shadow root; it won't affect other <p> elements on the page.
Shadow DOM and web components
Shadow DOM is one of the building blocks of web components, alongside custom elements and the <template> element. Together they let you build reusable components, like <my-date-picker>, that work in any framework or none.
Need help building modern, maintainable web interfaces? I.T. For Less can help — contact us.