> For the complete documentation index, see [llms.txt](https://petercheng7788.gitbook.io/developer-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://petercheng7788.gitbook.io/developer-note/programming-language/javascript/web-component.md).

# Web Component

## Custom element

### Introduction

* To encapsulate with custom html tag with javascript logic

### Example

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


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

```html
<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

![](/files/88s0FojmMSBmCXgURYLj)

* 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

```javascript
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

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/Web_Components>" %}

{% embed url="<https://stackoverflow.com/questions/40492330/difference-between-constructor-and-connectedcallback-in-custom-elements-v1>" %}
