Custom Elements: Creating Your Own HTML Tags

Custom Elements: Creating Your Own HTML Tags in JavaScript: Imagine if HTML didn't have a tag. You would have to make one using and a lot of messy JS.

Concept Explanation

Imagine if HTML didn't have a <button> tag. You would have to make one using <div> and a lot of messy JS. Web Components let you create your own real HTML tags like <user-card> or <video-player>.

The best part? They work in any framework (React, Vue, Angular) or even in a plain HTML file without any framework at all.


Syntax or Core Structure

The Class Definition

class MyGreeter extends HTMLElement {
  constructor() {
    super(); // Always call super first!
    console.log("I am born!");
  }

  connectedCallback() {
      this.innerHTML = "<h1>Hello from a Custom Element!</h1>";
  }
}

// Register the tag with the browser
customElements.define('my-greeter', MyGreeter);

Real World Example

Company Branding: A large company like Google or Adobe has thousands of different websites. They build their "Official Buttons" and "Auto-complete Boxes" as Web Components. This ensures that every site looks the same, regardless of whether the team uses React or just plain HTML.


Practice Exercises

  1. The Tag Maker: Create a custom element <color-box> that displays a 100x100 square of a specific color.
  2. The Capital Rule: Research why custom elements MUST have a hyphen (-) in their name (e.g., <my-tag>, not <mytag>).
  3. The Attribute Watcher: Research attributeChangedCallback and write a component that updates its text whenever you change its name attribute in the inspector.