Web Bytes - Shadow DOM

What is Shadow DOM and why is it important?

October 28, 2019
dev code mdn web

Web components have a key concept of encapsulation. Keep the html markup, css styling and js behavior separate from the rest of the page code. This enables to keep the DOM and code clean.

The Shadow DOM enables attachment of a hidden DOM structure to a visible page DOM element.

star wars storm trooper mini figure in shadow
unsplash-logoDaniel Cheung


Key Concepts

Shadow DOM tree structure is just like a regular DOM tree, but hidden.

  • Shadow host: The visible DOM tree node that connects to the shadow DOM tree.
  • Shadow tree: The shadow DOM tree.
  • Shadow boundary: The perimeter that separates the visible DOM from the shadown DOM.
  • Shadow root: The root node inside the hidden shadow DOM tree.

Illustration

shadow dom illustration

Analogy

The regular DOM is like the minifigure of stormtrooper being tossed up in the air. It’s individual pieces like nodes are visible and the tree structure is conspicuous.

The shadow DOM is like the classic action figure style stormtrooper. It’s nodes are fused and abstracted and the tree structure is not conspicuous.

star wars storm trooper mini figure tossed up
unsplash-logoDaniel Cheung


Famous Example

The video element has default browser controls, with various controls abstracted from view using the shadow DOM.

Practical Applications

Encapsulating styles and behavior helps in developing components and component libraries that can be dropped into and used in various applications.


Usage

Shadow DOM can be created in open or closed modes.

// can be manipulated by outer context js
Element.attachShadow({ mode: 'open'});

// or 

// cannot be manipulated by outer context js
Element.attachShadow({ mode: 'closed'});

Shadow DOM nodes can be manipulated using regular DOM APIs.

document.createElement();

Element.setAttribute('class','some-class');

Element.appendChild();

Closure

This fast article is intended to clarify and bolster web technology fundamentals.

References

MDN: Using shadow DOM

comments powered by Disqus