Every node lives in a tree, and every tree has a root: the document for nodes in the page, a document fragment for nodes that have not been inserted yet, the top element of a detached tree, or a shadow root for nodes inside a web component. node.getRootNode() returns that root. Components use it to find the shadow root they render into, to read activeElement there, or to check whether a node is in the page at all.
Write getRootNode(node, options) in root-node.js. It returns the same node as node.getRootNode(options), without calling it.
functiongetRootNode(node, options) // returns a Node
node: any node.
options: optional, { composed: boolean }. Without it, composed is false.
Returns the root of node's tree. With composed true, a shadow root is not a stopping point: the search goes on from the shadow root's host element, until the root is not a shadow root.
For a node in the page (an element or a text node), the root is the document. The document is its own root.
A node with no parent is its own root; a node in a detached tree has the tree's top node as its root.
A document fragment, including a template's content, is the root of the nodes inside it.
For a node inside a shadow tree, the root is the shadow root, both without options and with composed: false.
With composed: true, the search continues from the shadow root's host, through any number of nested shadow trees, to wherever the host's tree ends (the document, or a detached top element).
Closed shadow roots behave the same as open ones.
composed is read as true or false, so { composed: 1 } counts as true.
The answer follows the node's current position, and it works for very deep trees.
It works when Node.prototype.getRootNode does not exist.