自律カスタム要素の使い方
自律カスタム要素とは、<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>
参考記事