[ JS ] Custom Element

jwkwon0817·2023년 9월 25일
1

Web Front-end

목록 보기
5/5
post-thumbnail

오늘은 JS의 Custom Element를 생성하는 방법에 대해 알아봅시다.


기본틀

class YourClassName extends HTMLElement {
  constructor() {
    super();
    
    // HTML 내용
    this.innerHTML = `
      <div class="test">
        <h1>My name is</h1>
      </div>
    `;
  }
}

// Custom Element 정의 부분
// 첫 번째 파라미터: Custom Element 이름
// 두 번째 파라미터: Custom Element Class
customElements.define('your-element-name', YourClassName);

위와 같이 작성할 수도 있고 아래와 같이 작성할 수도 있습니다.

class YourClassName extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `
      <div class="test">
        <h1>My name is</h1>
      </div>
    `;
  }
}

customElements.define('your-element-name', YourClassName);

이런식으로 Custom Element를 정의하면 HTML 내에서 다음과 같이 Custom Element를 사용할 수 있습니다.

<your-element-name></your-element-name>

Attribute

만약 이 곳에 attribute를 추가하고 싶다면 다음과 같이 작성할 수 있습니다.

class YourClassName extends HTMLElement {
  constructor() {
    super();
    
    // this.getAttribute('attribute 이름')으로 attribute 값 가져올 수 있음.
    const yourAttribute = this.getAttribute('yourAttributeName');
    this.innerHTML = `
	  <div class="test">
		<h1>My name is ${ yourAttribute }</h1>
	  </div>
    `;
  }
}
<your-element-name yourAttributeName="yourName"></your-element-name>

Attribute 변경 감지

만약 Attribute가 변경되는지 감지하고 싶다면 아래 코드를 사용하면 됩니다.

class MyElement extends HTMLElement {
  constructor() {
      super();
	const name = this.getAttribute('name');
	this.innerHTML = `
	  <label>email input ${ name }</label>
	  <input>
	`;
  }
			
  static get observedAttributes() {
	return [ 'yourAttributeName' ]; // 감지할 Attribute 이름들
  }
			
  attributeChangedCallback() {
    // your code
  }
}

Example 1)

class MyElement extends HTMLElement {
  constructor() {
      super();
	const name = this.getAttribute('name');
	this.innerHTML = `
	  <label>email input ${ name }</label>
	  <input>
	`;
  }
			
  static get observedAttributes() {
	return [ 'yourAttributeName' ];
  }
			
  attributeChangedCallback() {
    console.log(this.getAttribute('yourAttributeName');
  }
}

Example 2)

class MyElement extends HTMLElement {
  constructor() {
      super();
	const name = this.getAttribute('name');
	this.innerHTML = `
	  <label>email input ${ name }</label>
	  <input>
	`;
  }
			
  static get observedAttributes() {
	return [ 'yourAttributeName' ];
  }
			
  attributeChangedCallback() {
   	// SPA(React, Vue)처럼 재렌더링 가능
    this.innerHTML = `
	  <label>email input ${ name }</label>
	  <input>
	`
  }
}
profile
SRIHS 119th SW

1개의 댓글

comment-user-thumbnail
2023년 9월 26일

이걸 보고 html를 배우기로 결심했어요 히히

답글 달기