Web Compendium Sitemap

Web Components

HTML Templates

Custom Elements

Shadow DOM

Shadow DOM is used to attach a DOM tree to an element without exposing this tree to JavaScript or CSS. The regular non-shadow DOM is commonly referred to as "light DOM" to differentiate the two. [MDN]

Shadow DOM has two distinct modes, open or closed. Open Shadow DOM allows the tree to be accessed with the shadowRoot property [MDN] through JavaScript. Closed Shadow DOM is completely inaccessible from the outside. [MDN]

Declarative Shadow DOM is a mechanism to declare shadow DOM content in HTML instead of using JavaScript. This is useful with server-side rendering for example. To declare a shadow root, <template shadowrootmode> must be used. The attribute must be present during HTML parsing and cannot be added programmatically with JavaScript. Styling can be attached using <style> within <template>. [MDN, chrome-dev, caniuse, mfreed7/declarative-shadow-dom, whatwg/html#5465, webkit.org]

Styling can be applied to the Shadow either programmatically using CSSStyleSheet [MDN] or declaratively using the <style> element within a <template> element [MDN].

The id attribute is locally scoped within the shadow root so that multiple custom elements can use the same ID. This behaviour may cause problems when using attributes that refer to elements with the specific ID value (e.g. aria‑describedby). [dom.spec.whatwg.org, webplatform.news, nolanlawson.com]