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

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

vsftpd default directory

[Ubuntu] *.deb 파일 설치 방법

Offset out of range error in Kafka, 카프카 트러블슈팅

리눅스 (cron - 주기적 작업실행 데몬)

리눅스 (하드링크&소프트링크)

CDPEvents in puppeteer

Using venv in Python