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)
<number-count/>
<number-count/>

// Output
// created
// connected
// created
// connected

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

class NumberCount extends HTMLElement{

    let style = document.createElement("style");

    style.textContent = `
    .wrapper {
      position: relative;
    }`;

    constructor(){
        super(); 
    }

    connectedCallback(){
        const shadow = this.attachShadow({mode: 'open'}); 
        shadow.appendChild(style);
        const wrapper = document.createElement("div");
        wrapper.id ="wrapper";
        shadow.appendChild(wrapper);
    }
     
}

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

References

Last updated

Was this helpful?