DEV Community

Sri-Ni, Thirumalaa Srinivas
Sri-Ni, Thirumalaa Srinivas

Posted on

Web Bytes - Shadow DOM

What is Shadow DOM and why is it important?

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.

Alt Text

Photo by Daniel Cheung on Unsplash

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

Alt Text


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.

Alt Text

Photo by Daniel Cheung on Unsplash

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'});
Enter fullscreen mode Exit fullscreen mode

Shadow DOM nodes can be manipulated using regular DOM APIs.

document.createElement();

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

Element.appendChild();
Enter fullscreen mode Exit fullscreen mode

Closure

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

References

MDN: Using shadow DOM

Top comments (0)