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

댓글

이 블로그의 인기 게시물

The logs of the kubelet service

Using the MinIO API via curl

Install and run an FTP server using Docker

Screenshot of a web page using Puppeteer with a specific browser width, 웹페이지 스크린샷

CDPEvents in puppeteer

Using venv in Python

To switch to a specific tag in a Git repository

Delete topic on Kafka, 카프카 토픽 삭제하기

NodePort vs ClusterIP on Kubernetes, 쿠버네티스 서비스