Custom HTML Element Extending the – Ry- Jul 29 '14 at 18:32

  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58282/discussion-between-skibulk-and-minitech). – skibulk Jul 29 '14 at 18:33
  • 1 Answers1

    0

    Short answer: Use Object.create() for the prototype object. The following code allows you to extend the script element, and represents the way document.registerElement() is meant to be used.

    var scriptData = document.registerElement('script-data', {
        prototype: Object.create(HTMLScriptElement.prototype);
    });
    

    Long answer

    Consider this variation on your original code:

    var scriptDataProto = HTMLScriptElement.prototype;
    // The next statement throws a DOMException of type "NotSupportedError".
    var scriptData = document.registerElement('script-data', {
        prototype: scriptDataProto
    });
    

    The source of the exception is illustrated here:

    scriptDataProto === HTMLScriptElement.prototype; // true
    

    You're providing a reference to HTMLScriptElement.prototype, meaning that you want to use the exact same prototype for the custom script element you're creating. It's not very well documented yet, but the prototype you provide can't be a reference to any of the built-in HTML[*]Element prototypes; you have to provide a new prototype object.

    If you want to inherit from the <script> tag's prototype, then you have to create a new prototype object that inherits from HTMLScriptElement.prototype by using Object.create().

    var scriptDataProto = Object.create(HTMLScriptElement.prototype);
    scriptDataProto === HTMLScriptElement.prototype; // false
    

    If you'd like, you can then add new members to this prototype without affecting the base HTMLScriptElement.prototype.

    scriptDataProto.foo = function() {
        alert('Hello world!');
    };
    var scriptData = document.registerElement('script-data', {
        prototype: scriptDataProto
    });
    var element = new scriptData();
    element.foo(); // alerts "Hello world!"
    document.body.appendChild(element);
    element.onclick = element.foo;
    

    For further reading, HTML5 Rocks has a well-written article that really helped me understand how custom elements work.

    theftprevention
    • 4,625
    • 3
    • 16
    • 31