This page is not complete.

Shadow DOM provides encapsulation for DOM and CSS in a Web Component. Shadow DOM makes it so these things remain separate from the DOM of the main document. You can also use Shadow DOM by itself, outside of a web component.

Why would you want to keep some code separate from the rest of the page? One reason is that on a large site, for example, if the CSS is not carefully organized, the styling for the navigation can "leak" into the main content area where it was not intended to go, or vice-versa. As a site or an app scales, this kind of thing becomes difficult to avoid. 

Basic Shadow DOM

Shadow DOM must always be attached to an existing element. The element can be either a literal element in an HTML file, or an element created in the DOM by scripting. It can be a native element like <div> or <p>, or a custom element like <my-element>. You attach shadow DOM using Element.attachShadow() like in this example:

    <p id="hostElement"></p>
      // create shadow DOM on the <p> element above
      var shadow = document.querySelector('#hostElement')
        .attachShadow({mode: 'open'});

The example above adds shadow DOM to a literal <p> element that has no content. Nothing is displayed yet. Continuing with the same example, you can insert text into the shadow DOM above with code like the following, and it will display in the browser:

shadow.innerHTML = '<span>Here is some new text</span>';

Styling Shadow DOM

You use the <style> element to add CSS to shadow DOM. Using the same example, this code will make the shadow DOM text red:

  // Create shadow DOM
  var shadow = document.querySelector('#hostElement')
    .attachShadow({mode: 'open'});
  // Add some text to shadow DOM
  shadow.innerHTML = '<span>Here is some new text</span>';
  // Add some CSS to make the text red
  shadow.innerHTML += '<style>span { color: red; }</style>';

The parts of Shadow DOM

Shadow DOM consists of these pieces:

* The shadow-piercing combinator is not completely agreed on.


The root node of a DOM subtree that is rendered separately from a document's main DOM tree.
Enables access to the contents of an HTML <template> element.
Enables access to the name and assigned nodes of an HTML <slot> element.
Provides APIs that are shared between documents and shadow roots.


Specification Status Comment
The definition of 'shadow trees' in that specification.
Living Standard  
Shadow DOM Working Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Edge Opera Safari (WebKit)
Basic support 53.0 In development 16 43.0 10.0
Feature Android Webview Firefox Mobile (Gecko) Edge Opera Mobile Safari Mobile Chrome for Android
Basic support 53.0 No support 16 Yes Yes 53.0

Document Tags and Contributors

 Last updated by: equinusocio,