Search code examples
javascripthtmlcssecmascript-6ecmascript-5

Connected callback is not being called while creating custom html elements


I was trying to create a custom tag in HTML using JavaScript. I want to create the custom element using ES6 JavaScript syntax. I have written this code to create the custom element:

customElements.define('neo-element', NeoElement);
function NeoElement (){
    var ref =  Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
<neo-element></neo-element>

I have verified that NeoElement is extending HTMLElement properly, but still nothing is getting printed inside the <neo-element> tag.

Could anyone look at the code and tell me what am I missing in ES5 syntax ?


Solution

  • It's not working because you're calling customElements.define—and thereby upgrading your <neo-element> to an instance of NeoElement—before you've defined NeoElement.prototype, NeoElement.prototype.constructor, and NeoElement.prototype.connectedCallback.

    If you move customElements.define to the end it works fine:

    function NeoElement() {
        var ref = Reflect.construct(HTMLElement,[], this.constructor) ;
        return ref;
    };
    NeoElement.prototype = Object.create(HTMLElement.prototype);
    NeoElement.prototype.constructor = NeoElement;
    NeoElement.prototype.connectedCallback = function(){
        this.innerHTML = `<h1>Hello world</h1>`;
    };
    customElements.define('neo-element', NeoElement);
    <neo-element></neo-element>