HTML5 & Web APIs (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is the Shadow DOM (`attachShadow({ mode: 'open' })`)?
senior LevelCode ExampleSystem Design
In Simple Words: Provides true DOM and CSS scoping isolation:
- Styles defined inside a Shadow Root never leak out into the main document.
- Global styles in the main document never bleed into the Shadow DOM.
javascript
class EncapsulatedWidget extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
/* Scoped styles! Does not affect any button outside this widget */
button { background: purple; color: white; padding: 10px; }
</style>
<button>Scoped Button</button>
`;
}
}
customElements.define('encapsulated-widget', EncapsulatedWidget);