getRootNode() 方法在 节点 interface returns the context object's root, which optionally includes the shadow root if it is available.

句法

var root = node.getRootNode(options);
					

参数

选项 可选
An object that sets options for getting the root node. The available options are:
  • composed : A 布尔 that indicates whether the shadow root should be returned ( false , the default), or a root node beyond shadow root ( true ).

返回

An object inheriting from 节点 . This will differ in exact form depending on where you called getRootNode() ; for example:

  • Calling it on an element inside a standard web page will return an HTMLDocument object representing the entire page.
  • Calling it on an element inside a shadow DOM will return the associated ShadowRoot .

范例

The first simple example returns a reference to the HTML/document node:

rootNode = node.getRootNode();
					

This more complex example shows the difference between returning a normal root, and a root incuding the shadow root. (See the full source code ):

<!-- source: https://github.com/jserz/js_piece/blob/master/DOM/Node/getRootNode()/demo/getRootNode.html -->
<div class="js-parent">
  <div class="js-child"></div>
</div>
<div class="js-shadowHost"></div>
<script>
  // works on Chrome 54+,Opera 41+
  var parent = document.querySelector('.js-parent'),
      child = document.querySelector('.js-child'),
      shadowHost = document.querySelector('.js-shadowHost');
  console.log(parent.getRootNode().nodeName); // #document
  console.log(child.getRootNode().nodeName); // #document
  // create a ShadowRoot
  var shadowRoot = shadowHost.attachShadow({mode:'open'});
  shadowRoot.innerHTML = '<style>div{background:#2bb8aa;}</style>'
      + '<div class="js-shadowChild">content</div>';
  var shadowChild = shadowRoot.querySelector('.js-shadowChild');
  // The default value of composed is false
  console.log(shadowChild.getRootNode() === shadowRoot); // true
  console.log(shadowChild.getRootNode({composed:false}) === shadowRoot); // true
  console.log(shadowChild.getRootNode({composed:true}).nodeName); // #document
</script>
					

规范

规范 状态 注释
DOM
The definition of 'getRootNode()' in that specification.
实时标准 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
getRootNode Chrome 54 Edge 79 Firefox 53 IE No Opera 41 Safari 10.1 WebView Android 54 Chrome Android 54 Firefox Android 53 Opera Android 41 Safari iOS 10.3 Samsung Internet Android 6.0

图例

完整支持

完整支持

不支持

不支持

元数据

  • 最后修改: