DEV Community

John Peters
John Peters

Posted on • Edited on

Web Components

A Simple Web Component's folder structure may look like this:
Web Component Folder Structure

The HTML file for the layout and the JS file to register the functionality.

Define a Custom Element

customElements.define('simple-custom', ...
Enter fullscreen mode Exit fullscreen mode

The reserved word customElements is a part of the CustomElementRegistry which is an interface in the DOM.

The define function can take multiple parameters:

define(name, constructor)
define(name, constructor, options)

This use of the define function gives the custom-element a name, and it defines the implementation of the class.

customElements.define('simple-custom',
  class extends HTMLElement {
    constructor() {
      super();
...
Enter fullscreen mode Exit fullscreen mode

It is a class definition which extends an HTMLElement followed by a constructor which must call super() first.

Creating the HTML Content

customElements.define('simple-custom',
  class extends HTMLElement {
    constructor() {
      super();
      const divElem = this.createHTMLContent();

Enter fullscreen mode Exit fullscreen mode
    createHTMLContent() {
      const divElem = document.createElement('div');
      divElem.textContent = this.getAttribute('text');
      return divElem;
    }
Enter fullscreen mode Exit fullscreen mode

Attaching a Shadow

customElements.define('simple-custom',
  class extends HTMLElement {
    constructor() {
      super();
      const divElem = this.createHTMLContent();
      this.createShadow(divElem);
    }
Enter fullscreen mode Exit fullscreen mode
    createShadow(divElem) {
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(divElem);
    }

Enter fullscreen mode Exit fullscreen mode

And the HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>:defined demo</title>
    <script src="main.js" defer></script>
    <style>
      p {
        background: yellow;
      }

      simple-custom {
        background: cyan;
      }

      :defined {
        font-style: italic;
      }

      simple-custom:not(:defined) {
        display: none;
      }

      simple-custom:defined {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1><code>:defined</code> demo</h1>

    <simple-custom text="Custom element example text"></simple-custom>

    <p>Standard paragraph example text</p>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

Result

Top comments (0)