Custom Element Illegal Constructor

Viewed 2242

This code gives an "Illegal Constructor" Error, can anybody tell me why?

class MyCustomElement extends HTMLElement {
  constructor(){
    super();
    // Other things
  }
}

const myFunc = () => {
  const instance = new MyCustomElement();
  console.log(instance);
}

myFunc();

2 Answers

After hours of searching I found that you MUST register the custom element BEFORE you can create an instance of it. I don't think this is in the spec, but this is the case for all browsers, also the error message sucks. I wish chrome would have just said "You must register a custom element before instantiating it" rather than "Illegal Constructor", which tells us almost nothing about what actually went wrong.

class MyCustomElement extends HTMLElement {
  constructor(){
    super();
    // Other things
  }
}

const myFunc = () => {
  const instance = new MyCustomElement();
  console.log(instance);
}

// Add this and it will start working
window.customElements.define('my-custom-element', MyCustomElement);

myFunc();

Note that you can create a custom element before it is defined by using document.createElement().

This element will be created as an unknown element and then only upgrade to a custom element when defined.

class MyCustomElement extends HTMLElement {
  constructor(){
    super()
    console.log( 'created' )
  }
}

const myFunc = () => {
  const instance = document.createElement( 'my-custom-element' )
  console.log( instance )
  document.body.appendChild( instance )
}

myFunc()

customElements.define( 'my-custom-element', MyCustomElement )

Related