WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 45 of 100

What is the Shadow DOM, and how does it help with web component encapsulation?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

The Shadow DOM is a browser technology that allows developers to encapsulate the HTML, CSS, and JavaScript of a web component, preventing it from being affected by styles or scripts from the rest of the page. This helps to prevent conflicts between the component and other parts of the page, improving code maintainability and reducing the risk of errors.

Here’s an example of how to create a web component using the Shadow DOM:

    // Define the web component using the Shadow DOM
    class MyComponent extends HTMLElement {
        constructor() {
            super();
            const shadowRoot = this.attachShadow({ mode: 'open' });
            shadowRoot.innerHTML = `
            <style>
            /* Styles for the component go here */
            :host {
                display: block;
                border: 1px solid black;
                padding: 10px;
            }
            </style>
            <p>This is my component!</p>
            `;
        }
    }
    
    // Register the web component with the browser
    customElements.define('my-component', MyComponent);

In this example, we define a web component using the MyComponent class, which extends the HTMLElement class. In the constructor of the component, we use the attachShadow method to create a new Shadow DOM for the component. The mode parameter is set to ’open’ to allow the component to be styled externally.

Inside the Shadow DOM, we define the HTML and CSS for the component. The :host selector is used to style the root element of the component. By using the Shadow DOM, these styles will only apply to the component and will not affect other parts of the page.

Finally, we register the web component using the customElements.define method, which tells the browser how to render the component when it is included in an HTML document.

The Shadow DOM is an important technology for web component encapsulation, as it allows developers to create components that are self-contained and do not interfere with other parts of the page. This helps to reduce the complexity of web applications and improve code maintainability.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics