2つの異なるタイプのカスタム要素を定義できる:
これは、extendsオプションなしで定義されている。これらのタイプのカスタム要素は、定義された名前と同じローカル名を持つ。
これは、extendsオプションで定義されている。これらのタイプのカスタム要素は、extendsオプションで渡される値と同じローカル名を持ち、定義された名前はis属性の値として使用され、したがってこれは妥当なカスタム要素名でなければならない。
JavaScript:
class WordCount extends HTMLParagraphElement{ constructor(){ super(); } } customElements.define('word-count', WordCount, { extends: 'p' });
↑ extendsオプション付き
HTML:
<p is="word-count"></p>
この節は非規範的である。
自律カスタム要素を作成する方法を説明するために、国旗の小さなアイコンのレンダリングをカプセル化するカスタム要素を定義してみよう。私たちの目標は、次のように使用できるようにすることである:
<flag-icon country="nl"></flag-icon>
これを行うには、まずカスタム要素のクラスを宣言し、HTMLElement を拡張する:
class FlagIcon extends HTMLElement { constructor() { super(); this._countryCode = null; } static get observedAttributes() { return ["country"]; } attributeChangedCallback(name, oldValue, newValue) { // name will always be "country" due to observedAttributes this._countryCode = newValue; this._updateRendering(); } connectedCallback() { this._updateRendering(); } get country() { return this._countryCode; } set country(v) { this.setAttribute("country", v); } _updateRendering() { // Left as an exercise for the reader. But, you'll probably want to // check this.ownerDocument.defaultView to see if we've been // inserted into a document with a browsing context, and avoid // doing any work if not. } }
次に、要素を定義するために次のクラスを使用して必要がある:
customElements.define("flag-icon", FlagIcon);
この時点で、上記のコードは動作する。flag-icon タグを見るたびに、パーサーは FlagIcon クラスの新しいインスタンスを作成し、要素の内部状態を設定し、レンダリングを更新するために使用する(適切な場合)、新しい country 属性についてコードに伝える。
DOM API を使用して flag-icon 要素を作成することもできる:
const flagIcon = document.createElement("flag-icon") flagIcon.country = "jp" document.body.appendChild(flagIcon)
最後に、カスタム要素コンストラクター自体を使用することもできる。つまり、上記のコードは次のコードと同じである:
const flagIcon = new FlagIcon() flagIcon.country = "jp" document.body.appendChild(flagIcon)
¶省く
カスタム要素は、カスタムである要素となる。非公式には、そのコンストラクターおよびプロトタイプが、ユーザー・エージェントによってではなく、著者によって定義されていることを意味する。この著者が提供するコンストラクター関数をカスタム要素コンストラクターと呼ぶ。
2つの異なるタイプのカスタム要素を定義できる:
カスタム要素が作成された後、is 属性の値を変更しても、is 値として要素に保存されるため、要素の動作は変更されない。