How can I create instances of customized builtins?

72 Views Asked by At

I'm writing a JSX factory for vanilla JS, but I can't seem to get customized builtins to work.

If I define a

customElements.define('x-hi', class extends HTMLElement { })

I can just

document.createElement('x-hi')

to get an instance, how can I get an instance of this :-

customElements.define('x-hello', class extends HTMLButtonElement { }, { extends: 'button' })
1

There are 1 best solutions below

0
On BEST ANSWER
class Hello extends HTMLButtonElement { }
customElements.define('x-hello', Hello, { extends: 'button' });
new (customElements.get('x-hello'))() instanceof Hello
// --> true

You can also do it with normal custom elements, but you should use document.createElement as the custom element may be defined later on in the code.

You're probably doing something like this in your factory:

const el = document.createElement(tagName);
for (let attrName in attrs) el.setAttribute(attrName, attrs[attrName]);

When setting is to x-hello on an already created HTMLButtonElement, you can't change it's prototype to have it become a Hello