It is possible to define custom functions on custom elements?
Something like:
var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function () { ... };
document.registerElement('custom-el', {
prototype: proto
});
And calling the method on the element:
var istance = document.createElement('custom-el');
instance.customMethod();
Yes, of course.
Your example works as you can see in the code snippet below:
New answer for Custom Elements v1
class CE extends HTMLElement {
customMethod() {
console.log( 'customMethod called' )
}
}
customElements.define( 'custom-el', CE )
var instance = document.createElement( 'custom-el' )
instance.customMethod()
Old answer for Custom Elements v0 (deprecated)
var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function() {
console.log('customMethod called')
};
document.registerElement('custom-el', {
prototype: proto
});
var instance = document.createElement('custom-el');
instance.customMethod();
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