Search code examples
javascriptweb-componentcustom-element

How to define a more customElements for same Class


I jsut tried to define new Custom Elements.

// the class
class MyEl extends HTMLElement {
  constructor() {
    // mandatory super call to upgrade the current context
    super();
    // any other Class/DOM related procedure
    this.setAttribute('custom-attribute', 'value');
this.innerText = 'new element';
  }
}

// its mandatory definition
customElements.define('my-el', MyEl);

// the JS way to create a custom element
const newMe = new MyEl();


document.body.appendChild(newMe);

Defining a new element of the same class will cause an error:
"Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry':
this constructor has already been used with this registry"

But i want to define new elements for same class. Could you suggest a way to display multiple items from the same class (MyEl).
Thank in advance!


Solution

  • customElements.define('my-el', MyEl) must be called only once to tell the browser you have a new <my-el> tag (aka to define a custom element).

    Then you can create multiple elements just by using new:

    const newMe1 = new MyEl();
    const newMe2 = new MyEl();
    

    Or createElement():

    const newMe1 = document.createElement( 'my-el' )
    const newMe2 = document.createElement( 'my-el' )
    

    Or, in the html code:

    <my-el></my-el>
    <my-el></my-el>