I want to create a shadow DOM for an element so I can display elements for a Chrome extension without the page styles affecting them.
When I looked at the documentation for Element.createShadowRoot
I saw it was deprecated so I checked out Element.attachShadow
. It said I had to provide an encapsulation mode but did not explain what the different modes do. I searched a bit but I wasn't able to find anything clearly explaining what the difference was.
What is the difference between the modes and which one should I use for what I am trying to achieve?
The closed mode of Shadow DOM has the single benefit which is to provide Web Component authors with the flexibility to decide how (if at all) to expose the Shadow Root of the component.
Shadow DOM serves for encapsulation. It allows a component to have its very own “shadow” DOM tree, that can't be accidentally accessed from the main document, may have local style rules, and more.
Shadow DOM:It refers to the browser's potential to add a subtree of DOM elements into the rendering of a document, but not into the DOM tree of the main document. Thus, it isolates the DOM and ensures that the DOM of a component is a separate element that won't appear in a global DOM.
Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.
With the open
mode you can access the Shadow DOM via the shadowRoot
property of the HTML element.
With the closed
mode you cannot. shadowRoot
will return null
.
You can use both modes for you want to achieve.
Here is a detailed explanation of the differences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With