Shadow DOM (Live Playground)
The Shadow DOM is a powerful feature in the JavaScript DOM that allows you to create encapsulated components with isolated styles and markup. It helps you create reusable components without affecting the rest of the page's styling or structure.
What is Shadow DOM?
Shadow DOM is a separate, hidden DOM tree that is attached to an element. It allows you to create a separate scope for your component's HTML, CSS, and JavaScript, preventing any styling or behavior leakage to the main document.
Creating a Shadow DOM
To create a Shadow DOM, you need to call the attachShadow()
method on the host element. The attachShadow()
method takes an object with a mode
property, which can be either open
or closed
. An open shadow root can be accessed from JavaScript outside the component, while a closed shadow root cannot.
const hostElement = document.createElement('div');
const shadowRoot = hostElement.attachShadow({ mode: 'open' });
Adding content to the Shadow DOM
You can add content to the Shadow DOM using the innerHTML
property or by appending elements to the shadow root.
shadowRoot.innerHTML = `
<style>
p {
color: blue;
}
</style>
<p>Hello, Shadow DOM!</p>
`;
const paragraph = document.createElement('p');
paragraph.textContent = 'Another paragraph in the Shadow DOM';
shadowRoot.appendChild(paragraph);
Accessing the Shadow DOM
To access the Shadow DOM, you can use the shadowRoot
property of the host element if the mode is set to open
. If the mode is closed
, you cannot access the shadow root from outside the component.
const hostElement = document.querySelector('#host-element');
const shadowRoot = hostElement.shadowRoot;
console.log(shadowRoot);
That's it! You've learned the basics of Shadow DOM and how to create encapsulated components using JavaScript. This will help you create more maintainable and modular web applications.