# 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>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://petercheng7788.gitbook.io/developer-note/programming-language/javascript/web-component.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
