MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Custom Elements Lifecycle (connectedCallback)0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
6.1Shadow DOM & Web Components Basics6.2Custom Elements Lifecycle (connectedCallback)6.3Virtual DOM Concepts & Reconciliation6.4MutationObserver API6.5ResizeObserver & IntersectionObserver APIs
HomeTutorialsJavaScript for AdvancedCustom Elements Lifecycle (connectedCallback)
Virtual DOM Concepts & Reconciliation

Custom Elements Lifecycle (connectedCallback)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Custom Elements are the core pillar of the W3C Web Components standard, enabling developers to define fully autonomous, reusable HTML tags with encapsulated behavior and state. Understanding the Custom Elements Lifecycle is essential for building framework-agnostic component libraries.


1. Defining a Custom Element

Custom elements extend HTMLElement and are registered with the browser's customElements registry:

1class UserAvatar extends HTMLElement {
2 constructor() {
3 super(); // Mandatory call to super()!
4 console.log('1. Constructor: Element instantiated.');
5 }
6}
7 
8// Custom element names MUST contain a hyphen (-) to avoid collisions with HTML tags!
9customElements.define('user-avatar', UserAvatar);

2. The 4 Lifecycle Callbacks

1┌─────────────────────────────────────────────────────────────┐
2│ CUSTOM ELEMENT LIFECYCLE │
3├──────────────────────────────┬──────────────────────────────┤
4│ connectedCallback() │ Element inserted into DOM │
5│ │ (Setup listeners, fetch data)│
6├──────────────────────────────┼──────────────────────────────┤
7│ disconnectedCallback() │ Element removed from DOM │
8│ │ (Cleanup timers, listeners) │
9├──────────────────────────────┼──────────────────────────────┤
10│ attributeChangedCallback() │ Observed attribute updated │
11├──────────────────────────────┼──────────────────────────────┤
12│ adoptedCallback() │ Element moved to new document│
13└──────────────────────────────┴──────────────────────────────┘

3. Observing Attribute Changes

To listen to attribute modifications via attributeChangedCallback(), you must declare a static getter named observedAttributes:

1class NotificationBadge extends HTMLElement {
2 static get observedAttributes() {
3 return ['count', 'theme']; // List attributes to monitor
4 }
5 
6 constructor() {
7 super();
8 this.attachShadow({ mode: 'open' });
9 }
10 
11 connectedCallback() {
12 this.render();
13 }
14 
15 // Triggered whenever 'count' or 'theme' is added, updated, or removed
16 attributeChangedCallback(name, oldValue, newValue) {
17 if (oldValue !== newValue) {
18 console.log(`Attribute "${name}" changed from "${oldValue}" to "${newValue}"`);
19 this.render();
20 }
21 }
22 
23 disconnectedCallback() {
24 console.log('Badge destroyed. Performing cleanup.');
25 }
26 
27 render() {
28 const count = this.getAttribute('count') || '0';
29 const theme = this.getAttribute('theme') || 'primary';
30 
31 this.shadowRoot.innerHTML = `
32 <style>
33 .badge {
34 display: inline-flex;
35 align-items: center;
36 justify-content: center;
37 padding: 0.25rem 0.5rem;
38 border-radius: 9999px;
39 font-weight: bold;
40 font-size: 0.75rem;
41 color: white;
42 }
43 .primary { background: #3b82f6; }
44 .danger { background: #ef4444; }
45 </style>
46 <span class="badge ${theme}">${count}</span>
47 `;
48 }
49}
50 
51customElements.define('notification-badge', NotificationBadge);

Live Mutation in Action:

1const badge = document.querySelector('notification-badge');
2badge.setAttribute('count', '5'); // attributeChangedCallback fires -> auto re-renders!
3badge.setAttribute('theme', 'danger');

4. Autonomous vs. Customized Built-in Elements

  1. 1
    Autonomous Custom Element: Extends HTMLElement. Used as <my-tag>.
  2. 2
    Customized Built-in Element: Extends a specific tag (e.g. HTMLButtonElement). Used with the is attribute:
1 class ConfirmButton extends HTMLButtonElement { ... }
2 customElements.define('confirm-button', ConfirmButton, { extends: 'button' });

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What naming convention is strictly required for Custom Element tag names?
Question 2
Which lifecycle callback fires when a Custom Element is attached to the active DOM?
Question 3
What must be defined on the class for attributeChangedCallback() to receive notifications when an attribute changes?
Question 4
Which lifecycle hook should be used to clear intervals and remove window event listeners?
Question 5
What base class must an autonomous Custom Element inherit from?
Next Lesson

Virtual DOM Concepts & Reconciliation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Shadow DOM & Web Components BasicsVirtual DOM Concepts & Reconciliation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext