Skip to the content.
component

Component

Web Components consist of three main technologies: Custom Elements, Shadow DOM, and HTML Templates.

Here’s a simple example of a Web Component using Custom Elements:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Custom Button Component</title>
  </head>
  <body>
    <!-- Define the custom button component -->
    <script>
      class CustomButton extends HTMLElement {
        constructor() {
          super();

          // Create a shadow root
          this.attachShadow({ mode: "open" });

          // Define the button element
          const button = document.createElement("button");
          button.textContent = "Click me!";
          button.addEventListener("click", () => alert("Button clicked!"));

          // Append the button to the shadow DOM
          this.shadowRoot.appendChild(button);
        }
      }

      // Register the custom element
      customElements.define("custom-button", CustomButton);
    </script>

    <!-- Use the custom button component -->
    <custom-button></custom-button>
  </body>
</html>

In the HTML body, <custom-button></custom-button> is used to insert an instance of the custom button component.

References