如何遍历 shadow DOM 中的元素 [英] how do I traverse elements within a shadow DOM
本文介绍了如何遍历 shadow DOM 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
div id=outer
#shadowRoot
div id=inner
button
在按钮的点击处理程序中,我想引用 divinner".在非 shadowDom 世界中,这将是 document.getElementById('inner')
,但在 shadow DOM 世界中等价物是什么?
In the click handler of the button, I want to reference the div "inner". In a non shadowDom world, this would be document.getElementById('inner')
, but what is the equivalent in a shadow DOM world?
注意.这是从自定义元素内部访问.我不是想从外面刺穿 shadow DOM.
NB. This is accessing from within the custom-element. I am not trying to pierce the shadow DOM from outside.
推荐答案
您可以使用绝对路径:使用 shadowRoot
来获取 Shadow DOM 内容.
You could use the absolute path: use shadowRoot
to get the Shadow DOM content.
document.querySelector( 'div#outer' ).shadowRoot.querySelector( 'div#inner' )
或者相对路径:使用getRootNode()
获取Shadow DOM根
Or the relative path: use getRootNode()
to get the Shadow DOM root
event.target.getRootNode().querySelector( 'div#inner' )
示例:
outer.attachShadow( { mode: 'open' } )
.innerHTML = `
<div id=inner></div>
<button>clicked</button>
`
outer.shadowRoot.querySelector( 'button' ).onclick = ev =>
ev.target.getRootNode().querySelector( 'div#inner' ).innerHTML = 'clicked'
<div id=outer></div>
这篇关于如何遍历 shadow DOM 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文