getRootNode Finds The Owning Tree

getRootNode reports whether a node belongs to the document or a shadow root, letting widgets branch on containment without leaking closed trees.

JavascriptSecurity Boundaries

Code

javascriptsnippet
19 lines
// getRootNode 返回节点所属的根:普通节点是 document,Shadow DOM 里是 shadow root
const host = document.createElement('div');
const shadow = host.attachShadow({ mode: 'closed' });
const inner = document.createElement('span');
shadow.append(inner);
document.body.append(host);

// 常规节点:根就是 document
console.log(document.body.getRootNode() === document);

// shadow 内部节点:根是 ShadowRoot,不是 document
console.log(inner.getRootNode() === shadow);
console.log(inner.getRootNode() instanceof ShadowRoot);

// 组件判断"我是否被放进 shadow 树",用来切换事件模型或作用域样式
function isInShadow(node) {
  return node.getRootNode() !== document;
}
console.log(isInShadow(inner), isInShadow(document.body));

getRootNode Finds The Owning Tree: reading the source

The snippet is organized around the function isInShadow.

Points of care

  • Nothing to vet in a supply-chain review — the file pulls in no packages.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

Entry signature: function isInShadow(node)

Key statements

return node.getRootNode() !== document;

Interactive Tools for This Topic

FAQ

Does getRootNode Finds The Owning Tree 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.