从 Shadow DOM 中获取 GetElementById [英] GetElementById from within Shadow DOM

查看:76
本文介绍了从 Shadow DOM 中获取 GetElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 shadow DOM 的自定义元素,它监听属性 target 的变化.
target 应该是我的组件应该附加到的元素的 ID.

I have a custom-element with shadow DOM, which listens to attribute target change.
target is supposed to be the ID of the element which my component is supposed to be attached to.

我尝试使用 querySelectorgetElementById 来获取外部 DOM 的元素,但它总是返回 null.

I've tried using querySelector and getElementById to get the element of the outer DOM, but it always returns null.

console.log(document.getElementById(target));
console.log(document.querySelector('#' + target));

以上都返回null.

有没有办法从 shadow DOM 中获取对父文档中元素的引用?

Is there a way to get a reference to the element in the parent document from within shadow DOM?

推荐答案

你只需要调用 Shadow Root.

You just have to call Shadow​Root.

this.shadowRoot.getElementById('target') 应该可以工作.

这是一个例子,get语法将对象属性绑定到函数.

Here's an example, the get syntax will bind an object property to a function.

get target() {
    return this.shadowRoot.getElementById('target');
}

这篇关于从 Shadow DOM 中获取 GetElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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