[英]How to access an element deep inside shadow-root
How can I access an element which is deep inside the shadow-root?如何访问影子根深处的元素?
<vaadin-combo-box>
#shadow-root
<vaadin-text-field id="input">
<vaadin-combo-box-dropdown-wrapper id="overlay">
#shadow-root(open)
<vaadin-combo-box-dropdown id="dropdown">
#shadow-root(open)
<vaadin-combo-box-overlay id="overlay">
#shadow-root(open)
<div part="overlay" id="overlay">
<div part="content" id="conent">
#shadow-root(open)
<div id="scroller">
<iron-list id="selector">
#shadow-root(open)
<vaadin-combo-box-item>
......
I want to style a vaadin-combo-box-item element but I don't know how to access this element.我想设置vaadin-combo-box-item元素的样式,但我不知道如何访问该元素。
There's no easy answer to that because you have to access a very deep DOM element.对此没有简单的答案,因为您必须访问非常深的 DOM 元素。
To make it little bit less painful you have to make a function which access provided shadow dom of element like this:为了让它不那么痛苦,你必须创建一个函数来访问提供元素的 shadow dom,如下所示:
const getShadowRoot = (elem, selector) => elem.shadowRoot.querySelector(selector);
const vaadinComboBox = getShadowRoot(document, 'vaadin-combo-box');
const vaadinTextField = getShadowRoot(vaadinComboBox, '#input');
const vaadinComboBoxWrapper = getShadowRoot(vaadinTextField, '#overlay');
const vaadinComboBoxDropdown = getShadowRoot(vaadinComboBoxWrapper, '#dropdown');
const vaadinComboBoxOverlay = getShadowRoot(vaadinComboBoxDropdown, '#overlay');
const vaadinComboBoxContent = getShadowRoot(vaadinComboBoxOverlay, '#conent');
const vaadinComboBoxSelector = getShadowRoot(vaadinComboBoxContent, '#selector');
const vaadinComboBoxItem = getShadowRoot(vaadinComboBoxContent, 'vaadin-combo-box-item');
Nevertheless, this amount of shadowDom elements looks like an architectural mistake尽管如此,如此数量的 shadowDom 元素看起来像是一个架构错误
I couldn't find an answer to get an element at an arbitrary depth.我找不到在任意深度获取元素的答案。 This is what I came up with;
这就是我想出的; you can use a function of the sorts to recursively descend into the shadow DOM, to get either the parent or the element itself:
您可以使用 function 之类的递归下降到影子 DOM,以获取父元素或元素本身:
function* descend(el, sel, parent) {
if (el.matches(sel)) {
yield parent ? el.parentElement : el;
}
if (el.shadowRoot) {
for (const child of el.shadowRoot.children) {
yield* descend(child, sel, parent);
}
}
for (const child of el.children) {
yield* descend(child, sel, parent);
}
};
Example use:使用示例:
const vid = [...descend(window.parent.document.querySelector("body"), "video", false)][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.