Search code examples
javascripthtmlweb-component

"Illegal invocation" error for call to member of newly-created Web components object


When I try to run the clear function in the following code snippet in Chrome, I get an Uncaught TypeError: Illegal invocation error.

I'm creating a web component with some functions for a text input. This is my first method but I keep getting that error and I have no clue what it could be.

var XEditProto = Object.create(HTMLInputElement.prototype);

XEditProto.clear = function() {
    this.value = '';
    return "Erased";
}

var Edit = document.registerElement('x-edit', {
    prototype: XEditProto,
    extends: 'input'
});
document.body.appendChild(new Edit());

Solution

  • var XEditProto = Object.create(HTMLInputElement.prototype);
    
    XEditProto.clear = function() {
        this.value = '';
        return "Erased";
    }
    
    var Edit = document.registerElement('x-edit', {
        prototype: XEditProto,
        extends: 'input'
    });
    var x = document.body.appendChild(new Edit());
    

    ...

    x.clear();
    

    Works as expected