본문으로 건너뛰기
  1. Posts/

Javascript Custom HTMLElement

·2 초· 0 · 0 ·
yna
custom element custom tag html css

JavaScript로 CustomElement 작성법 #

이 글은 Javascript로 Custom HTMLElemnet를 만드는 방법을 포함합니다.

이 글은 Node.js와 npm의 기능에 대해 설명하지 않습니다.

Custom Tag를 확인하기 위해 Node와 npm(node package manager)를 사용했습니다.(별도의 환경에서도 확인 가능합니다.)

Custom HTMLElement만들기 #

custom-tag.js

class CustomElement extends HTMLElement {
    constructor() {
        super();
 		// Create a shadow root.
        const shadowRoot = this.attachShadow({ mode: "open" });
        const button = document.createElement("input");
        button.type = "button";
        button.value = "my button";
        shadowRoot.appendChild(button);
    }
}
customElements.define("my-custom-tag", CustomElement);

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>index</title>
        <script type="module" src="./custom-tag.js"></script>
    </head>
    <body>
        <my-custom-tag></my-custom-tag>
    </body>
</html>

Command 창을 띄워서 custom-tag.js, index.js가 있는 폴더로 이동합니다.

someDir>npm i -D serve
someDir>npx serve

   ┌──────────────────────────────────────────┐
   │                                          │
   │   Serving!                               │
   │                                          │
   │   - Local:    http://localhost:3000      │
   │   - Network:  http://127.0.0.1:3000      │
   │                                          │
   │   Copied local address to clipboard!     │
   │                                          │
   └──────────────────────────────────────────┘

 HTTP  2023. 10. 10. 오전 11:33:35 ::1 GET /
 HTTP  2023. 10. 10. 오전 11:33:35 ::1 Returned 200 in 20 ms
 HTTP  2023. 10. 10. 오전 11:33:35 ::1 GET /customtag.js
 HTTP  2023. 10. 10. 오전 11:33:35 ::1 Returned 200 in 2 ms
 HTTP  2023. 10. 10. 오전 11:33:35 ::1 GET /favicon.ico
 HTTP  2023. 10. 10. 오전 11:33:35 ::1 Returned 404 in 4 ms

서버가 시작되면 local url로 접속합니다.

picture01

위와 같이 custom tag가 생성되었습니다.

Custom Tag 생명 주기 콜백 #

connectedCallback() {
	// custom tag가 document의 DOM에서 연결 되었을 때마다 호출됩니다.
    console.log("connected");
}

disconnectedCallback() {
    // custom tag가 document의 DOM에서 연결해제 되었을 때마다 호출됩니다.
    console.log("this connected");
}

attributeChangedCallback(name, oldValue, newValue) {
	// custom tag의 속성이 변경 되었을 때 호출됩니다.
    // name = 변경된 속성 이름
    // oldValue = 변경되기 전 값
    // newValue = 새로운 값
    /* attributeChangedCallback 함수는 
     static get observedAttributes() {
    		return ['attrName'];
	} 와 함께 사용됩니다. */ 
    console.log(`${name} is changed. oldValue = ${oldValue}, newValue = ${newValue}`);
}

다음 포스트엔 커스텀태그의 스타일 변경과 활용 예제를 포스팅하겠습니다.