HTML, 커스텀 앨리먼츠로 새로운 태그 만들기

0verfl0w767·2024년 12월 28일
1

<settings-ui> 라는 태그도 있었나?

다양한 웹 코드를 보면, 종종 <settings-ui>와 같은 신기한 태그를 발견할 때가 있다.

하지만, 알다시피 <settings-ui>HTML에서 지원하는 태그가 아니다. 어디서 나왔을까?

Custom Elements

MDN docs: https://developer.mozilla.org/ko/docs/Web/API/Web_components/Using_custom_elements

MDN docs에도 사용법과 내용이 잘 정리 되어있다.

Custom Elements란?

Custom Elements는 HTML의 기능을 확장할 수 있는 웹 컴포넌트(Web Components) 기술이다.

이를 통해 사용자 정의 태그를 만들고, 이를 HTML 문서 내에서 사용할 수 있다.

즉, Custom Elements를 사용하면 새로운 HTML 태그를 정의하여 웹 페이지의 요소를 재사용 가능한 컴포넌트로 만들 수 있다.

Custom Elements의 장점

  • 재사용성: 한 번 정의한 Custom Element는 여러 곳에서 재사용할 수 있다.

  • 캡슐화: Shadow DOM을 사용하여 스타일과 구조를 다른 요소와 독립적으로 캡슐화할 수 있다.

Shadow Dom 이란?

https://leeproblog.tistory.com/185

위에 블로그에 내용이 잘 정리 되어있다. 읽어보면 좋을 듯.

Custom Elements 사용 예시

bold, 24px, Arial 폰트로 스타일링된 <velog-wow>라는 Custom Element를 정의하는 예시를 들겠다.

<html>...</html>

<!DOCTYPE html>
<html lang="ko">
  <body>
    <velog-wow>Velog 와우!</velog-wow>
    <script>...</script>
  </body>
</html>

<script>...</script>

class VelogTest extends HTMLElement { // Custom Element 정의 클래스
  constructor() {
    super(); // HTMLElement 상속

    // Shadow DOM을 사용하여 스타일과 콘텐츠를 캡슐화
    const shadow = this.attachShadow({mode: 'open'}); // Shadow DOM 활성화

    // 텍스트 요소 생성
    const text = document.createElement('span'); // <span> 요소 생성
    text.textContent = this.textContent;  // <velog-wow> 태그의 텍스트를 가져옴

    const style = document.createElement('style'); // 스타일 정의
    style.textContent = `
      span {
      font-family: 'Arial', sans-serif;
      font-size: 24px;
      font-weight: bold;
    }`;

    // Shadow DOM에 스타일과 텍스트 추가
    shadow.appendChild(style);
    shadow.appendChild(text);
  }
}

// 새로운 태그 'velog-wow'을 정의
customElements.define('velog-wow', VelogTest);

코드 결과

작동 방식

  • VelogTest라는 Custom Element 클래스가 정의된다. 이 클래스는 HTMLElement를 상속받고, 내부에서 Shadow DOM을 사용하여 컴포넌트를 캡슐화한다.

  • Custom Element가 페이지에서 사용될 때, 생성자(constructor)가 호출되고, Shadow DOM이 생성되어 외부와 독립적인 영역이 만들어진다.

  • Custom Element의 텍스트 내용(this.textContent)은 <span> 태그로 감싸져 Shadow DOM에 추가된다.

  • 스타일은 Shadow DOM 내에서만 적용되며, 이는 style.textContent로 정의된다.

  • 마지막으로 customElements.define()을 통해 <velog-wow> 태그가 Custom Element로 등록되어 사용 가능하다.

0개의 댓글