Categories
JavaScript Answers

How to Get a List of Registered Custom Elements with JavaScript?

Spread the love

Sometimes, we want to get a list of registered custom elements with JavaScript

In this article, we’ll look at how to get a list of registered custom elements with JavaScript

Get a List of Registered Custom Elements with JavaScript

To get a list of registered custom elements with JavaScript, we can use the global customElements.get method.

For instance, we can write:

class PopUpInfo extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({
      mode: 'open'
    });

    const wrapper = document.createElement('span');
    const info = document.createElement('span');
    info.innerText = 'foo'
    shadow.appendChild(wrapper);
    wrapper.appendChild(info);
  }
}

customElements.define('popup-info', PopUpInfo);
console.log(customElements.get('popup-info'))

to register the popup-info custom element.

Then we use the customElements.get method with the element tag name to check if it has been registered.

We created the PopUpInfo class that creates some span elements and attach them to the shadow DOM with appendChild.

shadow is the shadow DOM root, which is created by the this.attachShadow method.

We then call customElements.define with the tag name and custom element class to register the element.

Therefore, the console log should log the custom element class that we just created.

Conclusion

To get a list of registered custom elements with JavaScript, we can use the global customElements.get method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *