Shadow DOM

Damaris Göbel
2 min readMay 9, 2021

--

What is the Shadow DOM?

The Shadow DOM is a “DOM within a DOM”. It is an isolated DOM tree with its own elements and styles, completed isolated from the main DOM.

With Shadow DOM you can specify CSS style to a specific DOM subtree and isolate that subtree from the rest.

What is the DOM again?

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a web page. In other words, the browser creates a DOM of a webpage when the page is loaded. The DOM is a live representation of your page.

The DOM model is created as a tree of objects like this:

<!DOCTYPE HTML>
<html>
<head>
<title>My title</title>
</head>
<body>
<a href=”url”>My link</a>
<h1>My header</h1>
</body>
</html>

The DOM represents HTML as a tree structure of tags. Here’s how it looks:

… and how does Shadow DOM get in there?

The shadow DOM tree starts with a shadow root and is attached to an element of the regular DOM, but separated from its actual children.

The shadow host is the regular DOM node that the shadow DOM is attached to.

The shadow tree is the DOM tree inside the shadow DOM.

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM

Creating shadow DOM

To create shadow DOM for an element, call element.attachShadow():

This method takes a parameter as an options objects — mode, with a value of open or closed. Mode: open means you can access the shadow DOM using JavaScript, mode: closed means, you won’t be able to access the shadow DOM from the outside.

Creating shadow DOM for a custom element

When creating custom elements, shadow DOM comes in handy. Use custom elements API to register a new HTML tag and define its JS behavior. Every instance of <hello-world> will have this same prototype:

The custom element creates its own shadow DOM when an instance of <hello-world> is created. The CSS rules inside the <style> will be scoped to <hello-world>.

Why would you use shadow DOMs?

Scoped CSS:

  • CSS selectors from the outer page don’t apply inside your component.
  • Styles defined inside don’t bleed out. They’re scoped to the host element.
  • Encapsulating styles in your element’s shadow root ensures that it will work regardless of where it is used.

--

--

Damaris Göbel
Damaris Göbel

Written by Damaris Göbel

I like to do crazy things with CSS & JavaScript. My brain occasionally runs out of memory so I need to write down my thoughts.