dom snippets

Shadow DOM and shadow root

Tagged attachshadow, shadowroot, dom, root, shadow  Languages javascript

Shadow DOM is very important for web components because it allows specific sections of the HTML document to be completely isolated from the rest of the document. This means CSS styles that are applied to the DOM are not applied to the Shadow DOM, and vice versa.

The shadow DOM can only be accessed through the reference returned by attachShadow:

const shadowComponent =  document.getElementById('component').attachShadow({mode: 'open'}); 
const p = document.createElement('p'); 
p.setAttribute('class', 'title'); 
p.innerText = 'Lorem ipsum'; 

The shadow root can be styled with CSS:

const css = document.createElement('style'); 
css.innerText = ` 
  .title { 
      font-size: 2rem; 
      font-weight: bolder; 

Use templates and slots make it easier to create components:


Also see the Awesome Styled Components repository and the Styled Components project for inspiration: