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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
24 lines
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.
  • document exist 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

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.