Web Components: Working With Shadow DOM


. This was never an issue with Custom Elements that built their own shadow root internally.

But for a declarative Shadow DOM, this means that each element needs its own template, and they cannot be reused. With this newly-added feature, we can selectively clone components when it’s desirable:




Option 2: serializable:true

Enabling this option allows you to save a string representation of the content inside an element’s shadow root. Calling Element.getHTML() on a host element will return a template copy of the Shadow DOM’s current state, including all nested instances of shadowrootserializable. This can be used to inject a copy of your shadow root into another host, or cache it for later use.

In Chrome, this actually works through a closed shadow root, so be careful of accidentally leaking user data with this feature. A safer alternative would be to use a closed wrapper to shield the inner contents from external influences while still keeping things open internally:




Notice setHTMLUnsafe(). That’s there because the content contains