Explore my works and
side projects  here

Research, Design & Development

shadowDOM

by

What is the shadowDOM 🥷🏿?

Shadow DOM is a web standard that allows developers to encapsulate HTML, CSS, and JavaScript inside a web component, preventing it from interfering with the rest of the document. It creates a separate, isolated DOM subtree that is not affected by external styles or scripts.


Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.


Features

  • Encapsulation
    Styles and scripts inside a shadow DOM do not leak out, and external styles do not affect the shadowDOM.
  • Scoped Styles 
    CSS inside the shadow DOM applies only to its elements.
  • Custom Elements Support 
    Often used with Web Components to create reusable elements.
  • Shadow Root
    The root of the shadow DOM tree, which is attached to a normal DOM element.


// Select an element
const element = document.getElementById('element');

// Attach a shadow root
const shadowRoot = element.attachShadow({ mode: 'open' });

// Add content inside shadow DOM
shadowRoot.innerHTML = `
<style>
p {
  color: blue;
  font-weight: bold;
}
</style>
<p>This is inside the shadow DOM!</p>
`;

More about Web Components here.

Which essentially form the core fundamentals of most modern Javascript frameworks.

See the Pen web-component by Kurt Grüng (@kurtgrung) on CodePen.