如何访问 shadow-root 深处的元素
How to access an element deep inside 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>
......
我想设置 vaadin-combo-box-item 元素的样式,但我不知道如何访问该元素。
这个问题没有简单的答案,因为您必须访问非常深的 DOM 元素。
为了减轻一些痛苦,您必须创建一个函数来访问提供阴影 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');
然而,如此数量的 shadowDom 元素看起来像是架构错误
如何访问影子根深处的元素?
<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>
......
我想设置 vaadin-combo-box-item 元素的样式,但我不知道如何访问该元素。
这个问题没有简单的答案,因为您必须访问非常深的 DOM 元素。
为了减轻一些痛苦,您必须创建一个函数来访问提供阴影 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');
然而,如此数量的 shadowDom 元素看起来像是架构错误