CustomElementRegistry

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Some parts of this feature may have varying levels of support.

CustomElementRegistry インターフェイスは、カスタム要素の登録と、登録された要素を照会するためのメソッドを提供します。このインスタンスを取得するには、window.customElements プロパティを使用してください。

メソッド

CustomElementRegistry.define()

新しいカスタム要素を定義します。

CustomElementRegistry.get()

名前付きカスタム要素のコンストラクターを返します。カスタム要素が定義されていない場合は undefined を返します。

CustomElementRegistry.upgrade()

シャドウルートに接続する前であっても、直接カスタム要素をアップグレードします。

CustomElementRegistry.whenDefined()

指定された名前でカスタム要素が定義されたときに解決する空のプロミスを返します。そのようなカスタム要素が既に定義されていた場合、返されたプロミスは即座に履行状態になります。

以下のコードは word-count-web-component という例 (ライブデモも見てください) から持ってきています。カスタム要素のクラスを作成した後に、 CustomElementRegistry.define() メソッドを使用してカスタム要素を定義していることに注意してください。

js
// 要素のクラスを作成
class WordCount extends HTMLParagraphElement {
  constructor() {
    // コンストラクターでは常に super を最初に呼び出してください
    super();

    // 要素の親要素の語数を数える
    var wcParent = this.parentNode;

    function countWords(node) {
      var text = node.innerText || node.textContent;
      return text.split(/\s+/g).length;
    }

    var count = "Words: " + countWords(wcParent);

    // シャドウルートを生成
    var shadow = this.attachShadow({ mode: "open" });

    // テキストノードを生成し、語数を追加
    var text = document.createElement("span");
    text.textContent = count;

    // シャドウルートに追加
    shadow.appendChild(text);

    // 要素の内容が変化したとき、語数を更新
    setInterval(function () {
      var count = "Words: " + countWords(wcParent);
      text.textContent = count;
    }, 200);
  }
}

// 新しい要素を定義
customElements.define("word-count", WordCount, { extends: "p" });

メモ: CustomElementsRegistry は Window.customElements プロパティを通して利用可能です。

仕様書

Specification
HTML
# custom-elements-api

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
CustomElementRegistry
Customized built-in element support
define
Supports disabledFeatures static property
get
getName
upgrade
whenDefined

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
See implementation notes.