Shadow DOM

Draft
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.createShadowRoot() like in this example:

<html>
  <head></head>
  <body>
    <p id="hostElement"></p>
    <script>
      // create shadow DOM on the <p> element above
      var shadow = document.querySelector('#hostElement').createShadowRoot();
    </script>
  </body>
</html>

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:

<script>
  // 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>';
</script>

The parts of Shadow DOM

Shadow DOM consists of these pieces:

Document Tags and Contributors

 Contributors to this page: maybe, Demon000, robatron, Dan-Dascalescu, markg
 Last updated by: maybe,