HTML powers the web because it's easy to work with. By declaring a few tags, you can author a page in seconds that has both presentation and structure. However, by itself HTML isn't all that useful. It's easy for humans to understand a text- based language, but machines need something more. Enter the Document Object Model, or DOM.

Sometimes it's useful to find custom elements used on the page. To do so, you need to recursively traverse the shadow DOM of all elements used on the page.

Answering the reverse question is also possible. element.assignedSlot tells you which of the component slots your element is assigned to.

Shadow DOM is not a security feature. It's a lightweight tool for scoping CSS and hiding away DOM trees in component. If you want a true security boundary, use an .</p> <p>If you recall from shadow DOM's event model, events that are fired inside shadow DOM are adjusted to look like they come from the hosting element. For example, let's say you click an <input> inside a shadow root:</p> <h2>Light DOMslots</h2> <p>There are a couple of interesting things going on here. The first is that the custom element creates its own shadow DOM when an instance of <fancy-tabs> is created. That's done in the constructor(). Secondly, because we're creating a shadow root, the CSS rules inside the <style> will be scoped to <fancy-tabs>.</p> <p>Don't get me wrong. Shadow DOM is certainly a complex beast! But it's a beast worth learning. Spend some time with it. Learn it and ask questions!</p> <p>The focus event will look like it came from <x-focus>, not the <input>. Similarly, document.activeElement will be <x-focus>. If the shadow root was created with mode:'open' (see closed mode), you'll also be able access the internal node that gained focus:</p> <p>Custom DOM events which are fired on internal nodes in a shadow tree do not bubble out of the shadow boundary unless the event is created using the composed: true flag:</p> <p>You don't have to author web components that use shadow DOM. But when you do, you take advantage of its benefits (CSS scoping, DOM encapsulation, composition) and build reusable custom elements, which are resilient, highly configurable, and extremely reusable. If custom elements are the way to create a new HTML (with a JS API), shadow DOM is the way you provide its HTML and CSS. The two APIs combine to make a component with self-contained HTML, CSS, and JavaScript.</p> <p>Outside styles always win over styles defined in shadow DOM. For example, if the user writes the selector fancy-tabs { width: 500px; }, it will trump the component's rule: :host { width: 650px;}.</p> <p>In this case, the component will use black as the background value since the user provided it. Otherwise, it would default to #9E9E9E.</p> <p>Ever wonder how the <select> element renders a multi-select widget (instead of a dropdown) when you add the multiple attribute:</p> <p>Closed mode makes your component less flexible for end users. As you build web components, there will come a time when you forget to add a feature. A configuration option. A use case the user wants. A common example is forgetting to include adequate styling hooks for internal nodes. With closed mode, there's no way for users to override defaults and tweak styles. Being able to access the component's internals is super helpful. Ultimately, users will fork your component, find another, or create their own if it doesn't do what they want :(</p> <p>For the first time ever, we have an API primitive that does proper CSS scoping, DOM scoping, and has true composition. Combined with other web component APIs like custom elements, shadow DOM provides a way to author truly encapsulated components without hacks or using older baggage like <iframe>s.</p> <p>Users can tweak internal styles if the component's author provides styling hooks using CSS custom properties. Conceptually, the idea is similar to <slot>. You create "style placeholders" for users to override.</p> <p>There's another flavor of shadow DOM called "closed" mode. When you create a closed shadow tree, outside JavaScript won't be able to access the internal DOM of your component. This is similar to how native elements like <video> work. JavaScript cannot access the shadow DOM of <video> because the browser implements it using a closed-mode shadow root.</p> <h2>Light DOMvs ShadowDOM</h2> <p>Throughout this article, I'll be referring to a demo component (<fancy-tabs>) and referencing code snippets from it. If your browser supports the APIs, you should see a live demo of it just below. Otherwise, check out the full source on Github.</p> <p>A shadow root is a document fragment that gets attached to a “host” element. The act of attaching a shadow root is how the element gains its shadow DOM. To create shadow DOM for an element, call element.attachShadow():</p> <p>Shadow DOM composes different DOM trees together using the <slot> element. Slots are placeholders inside your component that users can fill with their own markup. By defining one or more slots, you invite outside markup to render in your component's shadow DOM. Essentially, you're saying "Render the user's markup over here".</p> <p>:host-context() can be useful for theming, but an even better approach is to create style hooks using CSS custom properties.</p> <p>Elements are allowed to "cross" the shadow DOM boundary when a <slot> invites them in. These elements are called distributed nodes. Conceptually, distributed nodes can seem a bit bizarre. Slots don't physically move DOM; they render it at another location inside the shadow DOM.</p> <p>Nope! You don't have to create web components that use shadow DOM. However, authoring custom elements that use Shadow DOM means you can take advantage of features like CSS scoping, DOM encapsulation, and composition.</p> <p>The functional form of :host(<selector>) allows you to target the host if it matches a <selector>. This is a great way for your component to encapsulate behaviors that react to user interaction or state or style internal nodes based on the host.</p> <h2>Light DOMLWC</h2> <p>Inheritable styles (background, color, font, line-height, etc.) continue to inherit in shadow DOM. That is, they pierce the shadow DOM boundary by default. If you want to start with a fresh slate, use all: initial; to reset inheritable styles to their initial value when they cross the shadow boundary.</p> <p>Notice our component is able to handle different configurations, but the flattened DOM tree remains the same. We can also switch from <button> to <h2>. This component was authored to handle different types of children… just like <select> does!</p> <h2>Lwc:dom=manual</h2> <p>Above is the result when <x-focus> is focused (user click, tabbed into, focus(), etc.), "Clickable Shadow DOM text" is clicked, or the internal <input> is focused (including autofocus).</p> <p>There are many options for styling web components. A component that uses shadow DOM can be styled by the main page, define its own styles, or provide hooks (in the form of CSS custom properties) for users to override defaults.</p> <p>The shadow DOM API provides utilities for working with slots and distributed nodes. These come in handy when authoring a custom element.</p> <p>The markup a user of your component writes. This DOM lives outside the component's shadow DOM. It is the element's actual children.</p> <p>If you've been following web components for the last couple of years, you'll know that Chrome 35+/Opera have been shipping an older version of shadow DOM for some time. Blink will continue to support both versions in parallel for some time. The v0 spec provided a different method to create a shadow root (element.createShadowRoot instead of v1's element.attachShadow). Calling the older method continues to create a shadow root with v0 semantics, so existing v0 code won't break.</p> <p>Shadow DOM is designed as a tool for building component-based apps. Therefore, it brings solutions for common problems in web development:</p> <h2>Litlight DOM</h2> <p>The DOM a component author writes. Shadow DOM is local to the component and defines its internal structure, scoped CSS, and encapsulates your implementation details. It can also define how to render markup that's authored by the consumer of your component.</p> <p>The slotchange event fires when a slot's distributed nodes changes. For example, if the user adds/removes children from the light DOM.</p> <p>When an event bubbles up from shadow DOM it's target is adjusted to maintain the encapsulation that shadow DOM provides. That is, events are re-targeted to look like they've come from the component rather than internal elements within your shadow DOM. Some events do not even propagate out of shadow DOM.</p> <p>The spec defines a list of elements that can't host a shadow tree. There are several reasons an element might be on the list:</p> <p>If you happen to be interested in the old v0 spec, check out the html5rocks articles: 1, 2, 3. There's also a great comparison of the differences between shadow DOM v0 and v1.</p> <p>Another option for focus is the delegatesFocus: true option, which expands the focus behavior of element's within a shadow tree:</p> <p>Closed mode prevents your custom element code from accessing its own shadow DOM. That's complete fail. Instead, you'll have to stash a reference for later if you want to use things like querySelector(). This completely defeats the original purpose of closed mode!</p> <p></p> <h2>Light domexample</h2> <p>Styling the component itself will only get you so far. But what happens if you want to style the internals of a component? For that, we need CSS custom properties.</p> <p>Shadow DOM is particularly useful when creating custom elements. Use shadow DOM to compartmentalize an element's HTML, CSS, and JS, thus producing a "web component".</p> <h2>Light domjavascript</h2> <p>Instead of populating a shadow root using .innerHTML, we can use a declarative <template>. Templates are an ideal placeholder for declaring the structure of a web component.</p> <p>Sometimes it's useful to know what elements are associated with a slot. Call slot.assignedNodes() to find which elements the slot is rendering. The {flatten: true} option will also return a slot's fallback content (if no nodes are being distributed).</p> <p>When the browser loads a web page it does a bunch of interesting stuff. One of the things it does is transform the author's HTML into a live document. Basically, to understand the page's structure, the browser parses HTML (static strings of text) into a data model (objects/nodes). The browser preserves the HTML's hierarchy by creating a tree of these nodes: the DOM. The cool thing about DOM is that it's a live representation of your page. Unlike the static HTML we author, the browser-produced nodes contain properties, methods, and best of all… can be manipulated by programs! That's why we're able to create DOM elements directly using JavaScript:</p> <p>In our world of web development, composition is how we construct apps, declaratively out of HTML. Different building blocks (<div>s, <header>s, <form>s, <input>s) come together to form apps. Some of these tags even work with each other. Composition is why native elements like <select>, <details>, <form>, and <video> are so flexible. Each of those tags accepts certain HTML as children and does something special with them. For example, <select> knows how to render <option> and <optgroup> into dropdown and multi-select widgets. The <details> element renders <summary> as a expandable arrow. Even <video> knows how to deal with certain children: <source> elements don't get rendered, but they do affect the video's behavior. What magic!</p> <p>Shadow DOM is just normal DOM with two differences: 1) how it's created/used and 2) how it behaves in relation to the rest of the page. Normally, you create DOM nodes and append them as children of another element. With shadow DOM, you create a scoped DOM tree that's attached to the element, but separate from its actual children. This scoped subtree is called a shadow tree. The element it's attached to is its shadow host. Anything you add in the shadows becomes local to the hosting element, including <style>. This is how shadow DOM achieves CSS style scoping.</p> <p>CSS selectors used inside shadow DOM apply locally to your component. In practice, this means we can use common id/class names again, without worrying about conflicts elsewhere on the page. Simpler CSS selectors are a best practice inside Shadow DOM. They're also good for performance.</p> <p>Shadow DOM removes the brittleness of building web apps. The brittleness comes from the global nature of HTML, CSS, and JS. Over the years we've invented an exorbitant number of tools to circumvent the issues. For example, when you use a new HTML id/class, there's no telling if it will conflict with an existing name used by the page. Subtle bugs creep up, CSS specificity becomes a huge issue (!important all the things!), style selectors grow out of control, and performance can suffer. The list goes on.</p> <p>If there are multiple levels of shadow DOM at play (say a custom element within another custom element), you need to recursively drill into the shadow roots to find the activeElement:</p> <p>Until browser support is widely available, the shadydom and shadycss polyfills give you v1 feature. Shady DOM mimics the DOM scoping of Shadow DOM and shadycss polyfills CSS custom properties and the style scoping the native API provides.</p> <p>The result of the browser distributing the user's light DOM into your shadow DOM, rendering the final product. The flattened tree is what you ultimately see in the DevTools and what's rendered on the page.</p> <p><select> is able to style itself differently based on the attributes you declare on it. Web components can style themselves too, by using the :host selector.</p> <p>One gotcha with :host is that rules in the parent page have higher specificity than :host rules defined in the element. That is, outside styles win. This allows users to override your top-level styling from the outside. Also, :host only works in the context of a shadow root, so you can't use it outside of shadow DOM.</p> <p>:host-context(<selector>) matches the component if it or any of its ancestors matches <selector>. A common use for this is theming based on a component's surroundings. For example, many people do theming by applying a class to <html> or <body>:</p> <p>A component can define zero or more slots in its shadow DOM. Slots can be empty or provide fallback content. If the user doesn't provide light DOM content, the slot renders its fallback content.</p> <p>Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.</p> <p>Shadow DOM is one of the three Web Component standards: HTML Templates, Shadow DOM and Custom elements. HTML Imports used to be part of the list but now are considered deprecated.</p> <h2>Light dommeaning</h2> <p>Over the years I've learned a thing or two about authoring web components. I think you'll find some of these tips useful for authoring components and debugging shadow DOM.</p> <p>If you remember from before, <slot>s do not move the user's light DOM. When nodes are distributed into a <slot>, the <slot> renders their DOM but the nodes physically stay put. Styles that applied before distribution continue to apply after distribution. However, when the light DOM is distributed, it can take on additional styles (ones defined by the shadow DOM).</p> <p>In this example, there are two slots: a named slot for the tab titles, and a slot for the tab panel content. When the user selects a tab, we bold their selection and reveal its panel. That's done by selecting distributed nodes that have the selected attribute. The custom element's JS (not shown here) adds that attribute at the correct time.</p> <p>Shadow DOM composition introduces a bunch of new fundamentals in web development. Before getting into the weeds, let's standardize on some terminology so we're speaking the same lingo.</p> <p>Shadow DOM fixes CSS and DOM. It introduces scoped styles to the web platform. Without tools or naming conventions, you can bundle CSS with markup, hide implementation details, and author self-contained components in vanilla JavaScript.</p>