admin管理员组文章数量:1401384
I have
div id=outer
#shadowRoot
div id=inner
button
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?
NB. This is accessing from within the custom-element. I am not trying to pierce the shadow DOM from outside.
I have
div id=outer
#shadowRoot
div id=inner
button
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?
NB. This is accessing from within the custom-element. I am not trying to pierce the shadow DOM from outside.
Share Improve this question edited May 15, 2020 at 17:01 Supersharp 31.3k11 gold badges102 silver badges147 bronze badges asked May 5, 2019 at 14:25 pinoyyidpinoyyid 22.4k17 gold badges75 silver badges124 bronze badges 2- Possible duplicate of Is it possible to access Shadow DOM elements through the parent document? – P Varga Commented May 5, 2019 at 15:11
- Rather than access through the parent document, I was trying to access from an event within the shadowRoot. – pinoyyid Commented May 5, 2019 at 15:42
1 Answer
Reset to default 8You could use the absolute path: use shadowRoot
to get the Shadow DOM content.
document.querySelector( 'div#outer' ).shadowRoot.querySelector( 'div#inner' )
Or the relative path: use getRootNode()
to get the Shadow DOM root
event.target.getRootNode().querySelector( 'div#inner' )
Example:
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>
本文标签: javascripthow do I traverse elements within a shadow DOMStack Overflow
版权声明:本文标题:javascript - how do I traverse elements within a shadow DOM - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744288268a2598988.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论