--- title: CustomElementRegistry slug: Web/API/CustomElementRegistry tags: - API - CustomElementRegistry - Interface - Web Components translation_of: Web/API/CustomElementRegistry ---
CustomElementRegistry
接口提供注册自定义元素和查询已注册元素的方法。要获取它的实例,请使用 {{domxref("window.customElements")}}属性。
undefined
。以下代码来自我们的 word-count-web-component 示例(see it live also)。 请注意我们如何使用 {{domxref("CustomElementRegistry.define()")}} 方法在创建其类后定义自定义元素。
// Create a class for the element class WordCount extends HTMLParagraphElement { constructor() { // Always call super first in constructor super(); // count words in element's parent element var wcParent = this.parentNode; function countWords(node){ var text = node.innerText || node.textContent return text.split(/\s+/g).length; } var count = 'Words: ' + countWords(wcParent); // Create a shadow root var shadow = this.attachShadow({mode: 'open'}); // Create text node and add word count to it var text = document.createElement('span'); text.textContent = count; // Append it to the shadow root shadow.appendChild(text); // Update count when element content changes setInterval(function() { var count = 'Words: ' + countWords(wcParent); text.textContent = count; }, 200) } } // Define the new element customElements.define('word-count', WordCount, { extends: 'p' });
规范 | 状态 | 备注 |
---|---|---|
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}} | {{Spec2("HTML WHATWG")}} | Initial definition. |
{{Compat("api.CustomElementRegistry")}}