Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Element Illegal Constructor

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();
like image 919
Dustin Poissant Avatar asked Nov 28 '25 00:11

Dustin Poissant


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();
like image 136
Dustin Poissant Avatar answered Nov 29 '25 14:11

Dustin Poissant


It worked for me when I added {extends: 'div'} to the options which is the third parameter to the define method, so my code was like this

class MyCustomElement extends HTMLDivElement {
  constructor(){
    super()
  }

  connectedCallback() {
    console.log("Custom element added to page.");
  }
}

window.customElements.define('my-custom-element', MyCustomElement, {extends: 'div'})

// then I exported it and used it in another class
export default MyCustomElement;

and I used it like so

// another-file.js

import MyCustomElement from '../path/to/custom-element-class-file.js'

//...
const customDiv = new MyCustomElement()

document.body.append(customDiv)

//...

even the connectedCallback method was called after the element got added to the DOM

like image 41
Paulos Ab Avatar answered Nov 29 '25 13:11

Paulos Ab