首页 > 解决方案 > ShadowRoot 以 Null 形式返回 - ShadowRoot 显示为打开

问题描述

我正在尝试在 Javascript 中选择 Shadow 根,以便我可以设置内部元素的样式。但是当使用 elem.shadowRoot 时,它返回 Null,尽管 ShadowRoot 是下一个元素。下面我粘贴了我的调试和结果图片

这是我第一次使用 shadowRoot,所以我可能会遗漏一些明显的东西。

console.log("target");
console.log(target);

console.log("target.firstChild");
console.log(target.firstChild);

console.log("target.shadowroot");
console.log(target.shadowRoot);

console.log("target.firstChild.shadowroot");
console.log(target.firstChild.shadowRoot);

console.log("ha-card");
console.log(target.querySelector("ha-card"));

调试结果

标签: javascripthtml

解决方案


代码示例是定位,target.shadowroot而不是 shadowroot 元素本身。

另请查看使用 firstChild 方法的文档。它可能定位不正确。


推荐阅读