This page is not complete.

Shadow DOM provides encapsulation for the JavaScript, CSS, and templating 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();

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 = '<p>Here is some new text</p>';

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').createShadowRoot();
  // Add some text to shadow DOM
  shadow.innerHTML = '<p>Here is some new text</p>';
  // Add some CSS to make the text red
  shadow.innerHTML += '<style>p { color: red; }</style>';

The parts of Shadow DOM

Shadow DOM consists of these pieces:

* The descendent combinator is likely to be deprecated in the future.

Document Tags and Contributors

 Last updated by: guraga1,