attachShadow Isolates Markup And Styles
attachShadow scopes markup and queries inside a shadow root and keeps its styles from leaking out; closed mode additionally hides the shadowRoot reference.
Code
const stage = document.createElement('div');
document.body.append(stage);
// open-mode shadow root: the markup and styles live inside a boundary that
// normal DOM queries cannot cross
const host = document.createElement('div');
stage.append(host);
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<style>p { font-weight: bold; }</style><p>inside shadow</p>';
// document-level queries cannot see past the shadow boundary
console.log('stage p count:', stage.querySelectorAll('p').length);
console.log('shadow p count:', root.querySelectorAll('p').length);
console.log('stage finds shadow p:', stage.querySelector('p') === null);
// styles defined inside the shadow do not leak onto light DOM siblings
const outside = document.createElement('p');
stage.append(outside);
console.log('outside styled by shadow:', getComputedStyle(outside).fontWeight === 'bold');
// closed mode additionally withholds the shadowRoot reference
const sealed = document.createElement('div');
sealed.attachShadow({ mode: 'closed' });
console.log('closed shadowRoot:', sealed.shadowRoot);How it works
Everything operates on top-level bindings: stage, host, root, outside.
What to watch for
- Zero-fetch snippet: every identifier resolves inside the language distribution.
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Putting it to use
Look for the stage p count:, shadow p count:, stage finds shadow p: prefixes when the file runs; they tie each line to its step.
Core lines
root.innerHTML = '<style>p { font-weight: bold; }</style><p>inside shadow</p>';
const root = host.attachShadow({ mode: 'open' });
const sealed = document.createElement('div');
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Does attachShadow Isolates Markup And Styles run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.