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.
<divid="parent"><!-- web component --> <my-componenttext="my personal text"></my-component></div><buttonid="button"onclick="removeElement()">Remove Element</button>
๐ 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)}