MediumBrowser APIs📖 Theory Question

What is Shadow DOM and when do you use it?

💡

Hint

Encapsulated DOM subtree — styles and JS don't leak in or out; foundation of Web Components

Full Answer

// Attach a shadow root to any element
const host = document.getElementById('my-widget');
const shadow = host.attachShadow({ mode: 'open' }); // or 'closed'

// Add content — fully encapsulated
shadow.innerHTML = `
  <style>
    /* This CSS is SCOPED to shadow DOM only */
    p { color: red; font-size: 1.5rem; }
    :host { display: block; border: 1px solid blue; }
  </style>
  <p>I'm in shadow DOM</p>
  <slot></slot>  <!-- slot: renders host element's children -->
`;

// 'open' mode: accessible via element.shadowRoot
host.shadowRoot.querySelector('p'); // works
// 'closed' mode: host.shadowRoot = null (truly private)

// <slot> — project host children into shadow DOM
// <my-card><h2>Title</h2></my-card>
// The <h2> is rendered where <slot> is placed

// Web Component using Shadow DOM
class MyButton extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>button { background: purple; color: white; }</style>
      <button><slot>Click me</slot></button>
    `;
  }
}
customElements.define('my-button', MyButton);
💡 Shadow DOM = CSS encapsulation + DOM encapsulation. Styles from the outside can't penetrate in (except CSS custom properties / variables), and internal styles can't leak out. This is how browser built-ins like <video> and <input type="date"> hide their internal structure.

More Browser APIs Questions

EasyWhat is the Fetch API and how do you handle errors correctly?EasyWhat is the difference between localStorage, sessionStorage, and cookies?MediumWhat are Web Workers and when should you use them?MediumWhat are Service Workers and what problems do they solve?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint