Skip to content

Learning Shadow DOM, Shadow host & Shadow Root

Learning Shadow DOM , Shadow Host and Shadow Root is the essential pieces of building web components.

This is the common to any JavaScript libraries or compiler that helping to build web component.

What is Actually Shadow DOM?

Shadow DOM is the way of encapsulating our custom HTML element that brings the power of Open Web Platform Standards.

The way of exposing our web component is the key aspect that we should understand before publishing it.

Criteria of Web Component

  • You want the web component to be modified from outside? (Via attributes, CSS styles).

Based on the answer for the above question, we can design it by setting mode property.

const shadowDOM = this.attachShadow({ mode: 'open' });

The mode open will enable us to modify our web component from outside whereas closed will protect the web component privacy.

<template>
  <div class="container">
    <span>Testing Web Component</span>
  </div>
</template>

Next, The Shadow Root gets constructed around .container element from the above code snippet.

This Shadow Root gives us the protection layer around our custom element like below.

Shadow Root – Keo

Next, The Shadow Host is the HTML element which comprise our web component.

In addition to these key parts, :host and :host-context() CSS selectors helps to query the element which comprises our web component.

References

Published inJavaScript