how do I traverse elements within a shadow DOM

﹥>﹥吖頭↗ 提交于 2020-01-15 09:09:04

问题


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.


回答1:


You 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>


来源:https://stackoverflow.com/questions/55992972/how-do-i-traverse-elements-within-a-shadow-dom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!