1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!-- We want this element to have a scoped style sheet. --> <div id="myElement">red</div> <!-- Even though it is going to have a style sheet that looks like this will be targeted, it won't be. The style sheet on the shadow dom of the other element won't effect this one. --> <div>black</div> <script> (function() { // Create the style element var style = document.createElement('style'); style.innerHTML = `* { color: red; }`; // Note: there's a lot of documentation on the web telling // you to use: // "CSSStyleSheet, replaceSync, and adoptedStyleSheets..." // these are only supported in Chromium browsers. // So I didn't use that. // Get the element in question. const myElement = document.querySelector('#myElement'); // Attach a shadow in open mode ("open" leaves the element.shadowRoot public) myElement.attachShadow({mode: 'open'}); // Give the shadowRoot html a slot to render the element's // children myElement.shadowRoot.innerHTML = `<slot></slot>`; // append the stylesheet to the innerHTML myElement.shadowRoot.appendChild(style); })(); </script> |