Search code examples
javascripthtmlweb-componentcustom-element

How to create custom elements, using web components?


I'm trying to create custom element ...

My first option:

JS:enter image description here

class AwesomeButtonComponent extends HTMLButtonElement {
    constructor() {
        super();

        this.addEventListener('click', () => {
            alert('Great job!');
        });
    }
}

customElements.define('awesome-button', AwesomeButtonComponent, {extends: 'button'});

HTML: <awesome-button>CLICK ME</awesome-button>


My second option:

JS:

customElements.define('awesome-button', Object.create(HTMLButtonElement.prototype), {
       extends: 'button'
    });

HTML: <awesome-button>CLICK ME</awesome-button>

08.07.2019 and <button is="awesome-button">CLICK ME</button>

Each my attempt turns out a simple element. How to correct create custom element, which extended from native?

enter image description here

js, vue, html5


Solution

  • To use customized built-in elements, you have to reference them differently (by using the is-attribute) see here

    class AwesomeButtonComponent extends HTMLButtonElement {
        constructor() {
            super();
    
            this.addEventListener('click', () => {
                alert('Great job!');
            });
        }
    }
    
    customElements.define('awesome-button', AwesomeButtonComponent, {extends: 'button'});
    <!doctype html>
    <html>
      <head>
        <title>Custom element</title>
      </head>
      <body>
        <button is="awesome-button">CLICK ME</button>
      </body>
    </html>

    Be aware that not all browsers (as of 2019-07-08) support "Customized built-in elements" yet