What is Shadow DOM

What is Shadow DOM?

Shadow DOM is a core part of the Web Components standard, allowing developers to encapsulate HTML, CSS, and JavaScript within a custom element. This encapsulation ensures that styles and behavior inside the component are isolated from the rest of the document, preventing conflicts between internal and external CSS or scripts.


How It Works

  1. Shadow Root: A shadow DOM is created inside a host element by attaching a shadow root, which acts as a separate document tree.
  2. Encapsulation: Elements within the shadow DOM don’t interfere with or inherit styles from the main DOM (unless explicitly designed to do so).
  3. Slots: The shadow DOM allows for content projection through <slot> elements, letting external content be placed inside the component.

Example of Shadow DOM in Action

<custom-element></custom-element>

<script>
  class CustomElement extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });

      shadow.innerHTML = `
        <style>
          p { color: red; }
        </style>
        <p>This is inside the shadow DOM</p>
      `;
    }
  }

  customElements.define('custom-element', CustomElement);
</script>

In this example, the <p> element inside the shadow DOM will remain unaffected by CSS from the main document. Even if the main page defines a different style for <p> elements, it won’t apply inside the shadow tree.


Modes of Shadow DOM

  • Open Mode: The shadow root is accessible through JavaScript with element.shadowRoot.
  • Closed Mode: The shadow root is hidden from external scripts.

Use Cases for Shadow DOM

  1. Web Components: Encapsulate reusable UI elements like modals, buttons, or dropdowns.
  2. Style Isolation: Prevent style leakage between a component and the main page.
  3. Browser UI Elements: Native elements like <video> and <input> use shadow DOM internally to structure their content and styles.

Limitations of Shadow DOM

  • Selectors like querySelector can’t access it directly: You need to explicitly traverse the shadow root or use utilities like Puppeteer’s pierce selector.
  • SEO Challenges: Content inside shadow DOM might not always be indexed properly by search engines.

Shadow DOM helps in building modular and maintainable code, making it an essential tool for modern web development【19†source】【20†source】.

댓글

이 블로그의 인기 게시물

Develop a Kafka producer to send messages to a Kafka topic

Using the MinIO API via curl

max_active_runs of Airflow

Boilerplate for typescript server programing

difference between truncate and truncate_preserve in hbase

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

Parasite of korean movie

Kafka consumer in a Spring Boot application using a scheduled task

To integrate Spring Boot with your gRPC service using Gradle, Java, and Avro

kafka polling vs listen