basic shadow-dom custom element

In this example below you will see how to do a basic shadow-dom custom element with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by WebReflection, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright WebReflection ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>basic shadow-dom custom element</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/WebReflection/basic-shadow-dom-custom-element-JMxPdv */
customElements.define('shadow-dom', class extends HTMLElement {
  connectedCallback() {
    if (this.hasChildNodes()) {
      const shadow = this.attachShadow(
        // mode open by default, closed as mode="closed"
        {mode: this.getAttribute('mode') || 'open'}
      );
      while (this.hasChildNodes()) {
        shadow.appendChild(this.firstChild);
      }
    }
  }
});

document.body.innerHTML =
`<div class="foo">
  I am rendered in the Light DOM.
  <shadow-dom>
    <div class="foo">
      I am rendered into the Shadow DOM.
      <style>
        .foo { border: 2px solid red; }
      </style>
    </div>
  </shadow-dom>
</div>`;

Comments