How to create new instance of an extended class of custom elements
Solution 1:
Blink, the web engine that currently implements Custom Element v1 (in Chrome v53+ for example) only supports autonomous custom elements: see open Blink bug.
If you want to define customized built-in elements (i.e. <button>
extension), you'll need to use a polyfill like the one from Web Reflection.
Alternatly, you can still use the Custom Element v0 syntax (document.registerElement
).
Update #3
Since october 2018, they work natively with Chrome 67+ and Firefox 63+ :-)
Solution 2:
class F_BTN extends HTMLButtonElement{
constructor(){
super(); // must call constructor from parent class
this.addEventListener(...);
.... // etc.
}
}
customElements.define("f-btn",F_BTN,{extends:'button'});
use inline:
<body> .... <f-btn>BTN_NAME</f-btn> ... </body>
or create append from javascript
var elm = new F_BTN(...options);
// F_BTN = customElements.get('f-btn') // in case F_BTN is out of scope
The problem is elm = document.createElement('f-btn')
doesn't work.
That is why I made my custom create_element function _E
_E = function (name, html) {
var $;
switch (true) {
case (name === '' || !name): // _E() -- a div
{
$ = document.createElement('div');
}
break;
case (!name.indexOf('<')): // _E('<h1><i>abc</i><b>A</b></h1>') -- sub_dom
{
$ = document.createElement('div');
$.innerHTML = name;
$ = $.firstElementChild;
}
break;
default:
var c = window.customElements.get(name);
if(c){
$ = new c(); // _E('f-btn') -- customElement
} else {
$ = document.createElement(name); // _E('button') -- htmlElement
}
}
if (html) $.innerHTML = html;
return $;
};
var elm1 = _E('f-btn'); parent.appendChild(elm1);