DEV Community

Cover image for What is the Shadow DOM
georg.dev
georg.dev

Posted on • Originally published at georg.dev

What is the Shadow DOM

Missing style encapsulation

As a web developer, you've probably dealt with the headaches of missing style encapsulation. A single broad CSS selector can unexpectedly mess up the UI somewhere else on your site.

Adding third-party UI libraries only complicates things. Do their CSS class names clash with yours? Will their buttons break yours? Maybe.

The partial solution

Frameworks like Angular or Vue.js offer some form of component-based style encapsulation. Others, like React, let you choose from various style encapsulation libraries, such as styled-components.[1]

However, their solutions typically offer only pseudo style encapsulation. Instead of fully isolating styles, they often just add prefixes or suffixes to CSS class names following some patterns that hopefully prevent name clashes.

Doesn't this feel like a workaround? It does to me.

Meme: Fixing broken water tank with flex tape

Shadow DOM to the rescue

The shadow DOM attempts to fix the issue of missing encapsulation.[2] It allows you to attach additional subtrees to the main DOM. With this API, you take an HTML node from your DOM and you simply attach a new subtree to it. We call the root node of this new subtree the shadow root. The neat part: styles don't cross this shadow root.

Meme: Gandalf shouting

This means, the styles of your subtree don't leak out into the main DOM. Also, the styles of your main DOM don't affect the encapsulated content of the shadow DOM. Moreover, the same encapsulation also applies to browser events. An onclick event originating from the shadow DOM will not bubble up to the root of the main DOM. Instead, it will end at the shadow root.

How the shadow DOM works

There are two different ways how you can set up the shadow DOM. If you want to understand the concept better, take a look at the imperative API. Otherwise, feel free to jump ahead to the declarative API since that one is usually preferred by most developers nowadays.

Imperative API

Heads up: the imperative API does not work for server-side rendering (SSR). If you need SSR, use the declarative approach instead.

Let's assume, we have a very basic HTML structure:

<body>
  <div><span>OUTSIDE the shadow DOM</span></div>
  <div id="host"></div>
</body>
Enter fullscreen mode Exit fullscreen mode

Let's go over this. Our DOM has a <body> element that contains two HTML nodes:

  • a <div> containing a <span> with the text OUTSIDE the shadow DOM,
  • a <div> with the ID host. This will be our host element to which we'll attach the shadow DOM.

Diagram of the initial HTML structure

Next, we get the reference to this <div> element and attach a shadow DOM to it. Then, for the sake of demonstration, we create another <span> and append it to the shadow DOM:

// get the reference to the div
const hostElement = document.querySelector("#host");

// attach a shadow DOM
const shadowDom = hostElement.attachShadow({ mode: "open" });

// create a new HTML node (just for demonstration)
const exampleElement = document.createElement("span");
exampleElement.textContent = "INSIDE the shadow DOM";

// append the new HTML node to the shadow DOM
shadowDom.appendChild(exampleElement);
Enter fullscreen mode Exit fullscreen mode

Now, the new structure looks like this:

Diagram of the HTML structure with added shadow DOM

If you inspect how this is rendered in the browser, you will see something like this:

<body>
  <div><span>OUTSIDE the shadow DOM</span></div>
  <div id="host">
    #shadow-root (open)
      <span>INSIDE the shadow DOM</span>    
  </div>
</body>
Enter fullscreen mode Exit fullscreen mode

You can see all these steps together in this short animated diagram:

Declarative API

Heads up: the declarative shadow DOM has only recently been implemented in the last remaining browsers and is not fully adopted yet.[3] If you use the declarative API, add the required polyfill to your application.[4]

With the declarative shadow DOM API, you can do the same that we did in the imperative example above in plain HTML:

<body>
    <span>Outside the shadow DOM</span>
    <div id="host">
      <template shadowrootmode="open">
        <span>Inside the shadow DOM</span>
      </template>
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

Notice that we used the <template> element here. The reason for this is that the <template> element has its own mechanism for rendering its content. If you want to learn more about it, check out my template API article.

References

  1. Library: styled-components
  2. MDN Docs: Using shadow DOM
  3. Can I Use: Declarative shadow DOM
  4. web.dev: Declarative shadow DOM polyfill

Top comments (2)

Collapse
 
dannyengelman profile image
Danny Engelman

Maybe enhance it with an extra example:



<my-component>
  <template shadowrootmode="open">

  </template>
</my-component>


Enter fullscreen mode Exit fullscreen mode
Collapse
 
georg-dev profile image
georg.dev

Thanks for the input, Danny! Very much appreciated! I didn't want to overwhelm readers who are new to the topic with a custom element. I will do another intro article specifically for the custom elements spec and after that a short post where I put all of the techniques together.