Web Component

Custom element

Introduction

  • To encapsulate with custom html tag with javascript logic

Example

class NumberCount extends HTMLElement{
    constructor(){
        super(); 
        console.log("created");
    }
    
    connectedCallback(){
        console.log("connected");
    }
    
    disconnectedCallback(){
        console.log("disconnected");
    }
    
}


customElements.define("number-count", NumberCount)

Lifecycle

  • When custom element is declared, constructor method will be called, the parent element can be undefined as the custom element is not appended into document tree

  • After the custom element is appended, the connectedCallback method will be executed

  • When the custom element is removed from tree, the disconnected Callback method will be executed

Shadow DOM

Introduction

  • Since none of the code inside a shadow DOM can affect anything outside it, it is very suitable for separating CSS to prevent duplication of CSS class name

Example

References

Last updated

Was this helpful?