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】.

댓글

이 블로그의 인기 게시물

To build a gRPC service with Gradle, Java, and Avro

The pierce selector in Puppeteer

how to describe kafka topics, 카프카 토픽 정보 확인하기

Using the MinIO API via curl

오늘의 문장2

[Ubuntu] update-alternatives(Symbolic Link 관리)

언어의 어순과 문화적 특징의 관계를 생각해봅니다.

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

PySpark Dataframe from HBase