problem class MyButton extends HTMLButtonElement { constructor(){ super(); // must call c" /> problem class MyButton extends HTMLButtonElement { constructor(){ super(); // must call c" /> problem class MyButton extends HTMLButtonElement { constructor(){ super(); // must call c"/>

Cutom Elements: Can't extend from button Illegal constructor

37 Views Asked by At
<my-button 
        id="elem" 
        >
        problem
       </my-button>


       <button>
        works
       </button>

class MyButton extends HTMLButtonElement  {
    constructor(){
        super(); // must call constructor from parent class
    }
}

  customElements.define("my-button", MyButton, { extends: 'button'});

My question is : why I didn't get my element like Button ? Just text

1

There are 1 best solutions below

0
Danny '365CSI' Engelman On

Note: Customized Built-In Elements do not work in Apple-Safari
And never will, here is Apples POV going back to 2013 (yes, Web Components are not a new fad)

Customized Built-In Elements notation is the original Element with an is= reference:
<button is="my-button">

Code below works in Chrome, Edge, FireFox and Opera

<button is="my-button" id="foo">Click Me!</button>
<button is="my-button" id="bar">Click Me!</button>

<script>
customElements.define("my-button", 
  class extends HTMLButtonElement  {
      connectedCallback(){
        console.log("connected", this.id);
        this.onclick = evt => console.log("You clicked", this.id);
      }
  }, { extends: 'button'});
 </script>

createElement notation:

let myButton = document.createElement("button", { is: "my-button" });

General advice

Stick to Autonomous Elements (extending from HTMLElement)

<my-button id="foo">Click Me!</my-button>
<my-button id="bar">Click Me!</my-button>

(create the my-button yourself)