LoginSignup
4
0

More than 3 years have passed since last update.

自律カスタム要素の使い方

Posted at

自律カスタム要素の使い方

自律カスタム要素とは、<app-custom-element>のようなこのままページにおける自作HTML要素のことです。組み込み要素から継承するものと違って、前者は継承元の動きを受け継いだうえで、ページには<p is="app-custom-element">のようにis属性の指定が必要であるに対して、自律カスタム要素は完全に0から作り上げたものです。中身の構築はshadow domをつけるのが一般的な手法です。


// 基礎の組み込みhtml要素からではなく、大本となるHTMLElementから継承する
class PopUpInfo extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // 自律カスタム要素にshadow domをつけるのが一般的な手法
    const shadow = this.attachShadow({ mode: 'open' });

    const info = document.createElement('span');
    info.setAttribute('class', 'info');

    // 自身に渡してきた属性をアクセスすることが可能
    const text = this.getAttribute('data-text');
    info.textContent = text;

    // Create some CSS to apply to the shadow dom
    const style = document.createElement('style');

    style.textContent = `
      .info {
        font-size: 0.8rem;
      }
    `;

    // Attach the created elements to the shadow dom
    shadow.appendChild(style);
    shadow.appendChild(info);
  }
}

// カスタム要素を登録する
customElements.define('pop-up-info', PopUpInfo);

ページでの使い方は以下のようです。

<pop-up-info data-text="Your card"></pop-up-info>

dev toolsで見たイメージは大体こんな感じです:
image.png

参考記事

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0