Search code examples
javascripthtmlpolymershadow-dom

Shadow-root sibling elements disappear on attachShadow() call


When I call host.attachShadow({mode: 'open'}) on a div containing a few elements inside, the contents of the div seemingly disappears. The elements are still visible from devtools but are no longer visible on screen.

It doesn't matter if i fill the shadowRoot with anything; as soon as the shadow is attached the div's children disappear.

Demo on codepen: https://codepen.io/anon/pen/VrBdOe

Why does the content disappear? I've seen it on websites so I know it's possible somehow. See the code for https://www.polymer-project.org/2.0/start/quick-tour for example, the <pw-shell> node has a shadow-root and several siblings co-existing. What's going on there?


Solution

  • The Shadow DOM content will replace the original DOM subtree of the host where it (the shadow root) is attached. That's the expected behaviour of a Shadow DOM (hence this name).

    You can make it appear by using the element in the Shadow DOM.

    host.attachShadow( { mode: 'open' } )
        .innerHTML = 'Original DOM: <slot></slot>, in the Shadow DOM'
    <div id=host>
    Lite DOM
    </div>

    You should read the tutorial about Shadow DOM for further details.