获取影子根主机元素 [英] Get shadow root host element

查看:53
本文介绍了获取影子根主机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将脚本插入元素的影子根目录时,是否可以引用宿主元素?

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/

推荐答案

我终于明白了.

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

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

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

您可以通过沿着DOM树走到影子根.

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

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/

这篇关于获取影子根主机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆