Node.getRootNode() - Web APIs 编辑

The getRootNode() method of the Node interface returns the context object's root, which optionally includes the shadow root if it is available.

Syntax

var root = node.getRootNode(options);

Parameters

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

Returns

An object inheriting from Node. 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.

Examples

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>

Specifications

SpecificationStatusComment
DOM
The definition of 'getRootNode()' in that specification.
Living StandardInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:112 次

字数:4186

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文