Search code examples
javascriptclassinstanceweb-component

JavaScript - Create elements using web component class


I have a web component that only works when some properties are set, when I create the component with Document.createElement() I can't pass properties then an error happens in my component.

Is it possible to create the component by creating an instance of the component class or something similar and be able to pass parameters to it's constructor?

customElements.define('x-card', class extends HTMLDivElement {
//...
}, { extends: 'div' });


Solution

  • You can create a new instance using new WCard. This requires having access to the class though.

    Please note that custom element names preferrably should not start with x-.

    So change your code:

    export class WCard extends HTMLDivElement {
    //...
    }
    
    customElements.define('w-card', WCard, { extends: 'div' });
    
    window.WCard = WCard;
    

    This allows you to call new on the class globally, or if your code imports the class.

    const wcard = new WCard(...args);