Introduction to Shadow DOM part 1

Danny Cornelisse
18-05-2017

Whenever you inspect a website you might find things that you never saw before. I noticed that a lot of website have this element called a #shadow-root. Wait, what is a shadow-root? Is is the same thing that lives under your bed?

The shadow DOM

No. Luckily, a shadow-root does not live under your bed. It lives in the DOM (document object model), except not really. A shadow-root is the root of a shadow DOM. A shadow DOM can be seen as a scoped DOM inside the regular DOM. That means that the elements in the shadow DOM are isolated from the elements in the normal DOM. A shadow DOM consist of:

  •  shadow host: The element that hosts the shadow DOM
  • shadow root: The root element that is attached to the shadow host
  • shadow tree: A scoped subtree of elements, can be anything

Sound familiar? Yes, it is kind of like an <iframe> element, which also has an isolated scope (not the <frame> element, please don’t use that). Since all elements in the shadow DOM are part of an isolated scope, this means:

  • The <style> element is also scoped, that means CSS is scoped!
  • All elements cannot be targeted by JavaScript of CSS from the regular DOM

That is awesome! Now, developers that don’t know how to write good CSS class names and CSS selectors have a way to apply style to elements that need specific styling! No more !important (please never use this, ever).

How to create a shadow DOM

How can I create a shadow DOM? It’s easy. First, create a shadow host:

My regular DOM

Find the element and call .attachShadow() on it:


const myShadowHost = document.querySelector('#my-shadow-host');
const myShadowRoot = myShadowHost.attachShadow({mode: 'open'});

//attach some html
myShadowRoot.innerHTML = '

My shadow DOM

\* h1 {color:red;} *\

';

The style that I wrote in the innerHTML

LEAVE A REPLY

you might also like