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();
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With