constructor()
an instance of custom element is created or upgraded.
connectedCallback()
custom element is appended into/moved in a document.
disconnectedCallback()
custom element is removed from the document.
attributeChangedCallback(attrName, oldVal, newVal)
one of the custom element’s attributes is added/removed/changed.
observed attributes are specified with static get observedAttributes().
adoptedCallback()
custom element is moved to a new document.
MDN ⟩
Google ⟩ - a.k.a lifecycle callbacks
📁 HTML
📁 JS
// ⭐️ 1. custom web componentclassMyComponentextendsHTMLElement {constructor(){ // debug infoconsole.log(`🐣 contructed ...`);// tell HTMLElement to initialize itselfsuper();// variablesconsttext=this.getAttribute('text') ||'Loren Ipsum';constsize=randomInt(12,50); // random font size// create elementconstelem=document.createElement('template');elem.innerHTML =MyComponent.template(text, size);// add to UIthis.appendChild(document.importNode(elem.content,true)); }// HTML tempaltestatictemplate(text, size) { return` <div style="font-size:${size}px">${text} (font-size: ${size}) </div> `; }/* -------- life-cycle triggers -------- */connectedCallback() { console.log(`🔌 connected ...`); } disconnectedCallback() { console.log(`❌ disconnected ...`); }attributeChangedCallback(attrName, oldVal, newVal) { console.log(`✏️ attribute "${attrName}" changed: ${oldVal} ➝ ${newVal}`); }/* To get the attributeChangedCallback() method to work correctly, we must add the static method observedAttributes() and return the properties that we want to observe. */staticgetobservedAttributes() { return ['text']; }/* --------- set/get `text` ---------- */settext(val) { this.setAttribute(`text`, val ??``); }gettext() { returnthis.getAttribute('text'); }} // ⭐️ 2. custom tag <my-component>// ⭐️⭐️ custom element names must contain a "hyphen".customElements.define('my-component', MyComponent);/* -------- button -------- */functionremoveElement() {constdiv=$('#parent');constelement=$('my-component');constbutton=$('#button');div.removeChild(element);button.disabled =true;}/* -------- helpers -------- */// $ ⭐️function$(selector, parent = document){returnparent.querySelector(selector);}// random integer between a and bfunctionrandomInt(a, b){returnMath.floor((Math.random() * (b - a +1)) + a)}
<divid="parent"><!-- web component --> <my-componenttext="my personal text"></my-component></div><buttonid="button"onclick="removeElement()">Remove Element</button>