Web Components

Reusable custom elements. A web component has 3 things: 1) Custom Elements 2) Shadow DOM 3) HTML Template. Use JavaScript Class to define custom elements and you can attach a shadow DOM (attachShadow) to the custom elements to keep things private and manipulate it outside the main DOM. The HTML Template can be the reusable markup not rendered on page.

The HTML Template introduced 2 new elements: <template> and <slot>.

<template id="juanitofatas">
  <p>Hello there!</p>
</template>
class juanitoFatasComponent extends HTMLElement {
  constructor() {
    super()
    // Creating the shadow root (Shadow DOM)
    let shadow = this.attachShadow({ mode: 'open' })

    let template = document.getElementById('juanitofatas')
    let templateContent = template.content

    let style = document.createElement('style');
    style.textContent = `
    background {
      color: white;
    }
    `

    // Add style to the shadow DOM
    shadow.appendChild(style)

    // Add custom HTML element to shadow DOM
    shadow.appendChild(templateContent.cloneNode(true))
  }
}

if (!window.customElements.get('juanitofatas')) {
  window.juanitoFatasComponent = juanitoFatasComponent
  window.customElements.define('juanitofatas', juanitoFatasComponent)
}

Now can just use it like so:

<juanitofatas></juanitofatas>