javascript 获取影子根宿主元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25339932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:23:50  来源:igfitidea点击:

Get shadow root host element

javascripthtmlgoogle-chromeshadow-dom

提问by Bart

When inserting a script into the shadow root of an element is there a way to refer to the host element?

将脚本插入元素的影子根时,有没有办法引用宿主元素?

var element = document.createElement('div');
var script = document.createElement('script');
script.innerHTML = 'console.log(host)'; // << How to get host element??

var shadow = element.createShadowRoot();
shadow.appendChild(script);

document.body.appendChild(element);

http://jsfiddle.net/9b1vyu4n/

http://jsfiddle.net/9b1vyu4n/

回答by Bart

I got this finally figured out.

我终于明白了这一点。

According to the specification (working draft) a ShadowRoothas a read only property called host. http://www.w3.org/TR/shadow-dom/#shadowroot-object

根据规范(工作草案),aShadowRoot有一个只读属性,称为host. http://www.w3.org/TR/shadow-dom/#shadowroot-object

interface ShadowRoot : DocumentFragment {
    ...
    readonly    attribute Element        host;
    ...
};

You can get to the shadow root by walking up the DOM tree.

您可以通过向上走 DOM 树到达影子根。

while(e.nodeType != 11) { // 11 = DOCUMENT_FRAGMENT_NODE
    e = e.parentNode;
}
var hostElement = e.host

In my case it was simpler since the shadow root was the parent node of the script itself.

就我而言,它更简单,因为影子根是脚本本身的父节点。

document.currentScript.parentNode.host

http://jsfiddle.net/9b1vyu4n/2/

http://jsfiddle.net/9b1vyu4n/2/

回答by darrylyeo

Node.getRootNode()was introduced in 2016.

Node.getRootNode()于 2016 年推出。

You can now access the host element like so:

您现在可以像这样访问宿主元素:

element.getRootNode().host