Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Web Components – Custom Elements | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 35 of 55

·HTML

Web Components – Custom Elements

12 min

Course progress64%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Creating a class that extends `HTMLElement` or a built‑in element
  • Registering the element with `customElements.define`
  • Using Shadow DOM for encapsulated markup and styles
  • Defining observed attributes and handling changes
  • Exposing custom events for external interaction

Defining Reusable Elements

Custom Elements let you create new HTML tags with encapsulated behaviour.

class MyButton extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'closed' });
    const btn = document.createElement('button');
    btn.textContent = this.getAttribute('label') || 'Click';
    btn.addEventListener('click', () => this.dispatchEvent(new CustomEvent('press')));
    shadow.appendChild(btn);
  }
}
customElements.define('my-button', MyButton);

Usage

<my-button label='Submit'></my-button>

Advanced features

  • Observed attributes – React to attribute changes with static get observedAttributes() and attributeChangedCallback().
  • Lifecycle callbacks – connectedCallback(), disconnectedCallback(), attributeChangedCallback() allow you to run code when the element is added/removed or when attributes change.
  • Shadow DOM – Provides encapsulated markup and styles; can be open (accessible via element.shadowRoot) or closed.
  • extends syntax – Create a custom element that extends an existing built‑in tag (HTMLButtonElement).

Quick checklist for custom elements

  1. Class extends HTMLElement (or a built‑in element)? ✅
  2. Registered with customElements.define? ✅
  3. Shadow DOM used for encapsulation (attachShadow)? ✅
  4. Lifecycle callbacks implemented as needed? ✅
  5. Custom events (dispatchEvent) used for communication? ✅

Tip: Keep the component API surface small – expose only the attributes and events that consumers need.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonText Formatting TagsContinue to lesson 36Web Components – Shadow DOMBack to HTML Course curriculum