customElement라는것을 알게되었다.

YEONGHUN KO·2022년 9월 12일
0

HTML - BASICS

목록 보기
3/6
post-thumbnail

이름에서도 알 수 있듯이 html에서 기본적으로 제공해주는 tag뿐만아니라 내가 직접 tag를 설정하고 그 tag에 해당하는 기능을 만들 수 있다.

예를 들어 <time-formatted> 라는 tag를 만든다고 하면 아래와 같이 tag의 이름과 그 tag에 기능을 불어넣어주는 class를 만들고 지정해주면 된다.

class TimeFormatted extends HTMLElement { // (1)

  connectedCallback() {
    let date = new Date(this.getAttribute('datetime') || Date.now());

    this.innerHTML = new Intl.DateTimeFormat("default", {
      year: this.getAttribute('year') || undefined,
      month: this.getAttribute('month') || undefined,
      day: this.getAttribute('day') || undefined,
      hour: this.getAttribute('hour') || undefined,
      minute: this.getAttribute('minute') || undefined,
      second: this.getAttribute('second') || undefined,
      timeZoneName: this.getAttribute('time-zone-name') || undefined,
    }).format(date);
  }

}

customElements.define("time-formatted", TimeFormatted); // (2)
<!-- (3) -->
<time-formatted datetime="2019-12-01"
  year="numeric" month="long" day="numeric"
  hour="numeric" minute="numeric" second="numeric"
  time-zone-name="short"
></time-formatted>

또 다시 신기한 기능을 배웠다. shadow dom이라는 것도 있다고 하는데 나중에 한 번 배워보자.

이 이외에 다양한 기능은 아래를 참고하자
https://ko.javascript.info/custom-elements

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글