0

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

2
  • I wouldn't recommend you to extend HtmlButtonElement as Safari and Opera don't support it, you should extend HtmlElement and have a button inside it or allow for button's to be inserted using a slot Commented Jul 8, 2019 at 7:59
  • Start by learning the basics in someone else his JSFiddle: jsfiddle.net/hasan3ysf/qzzs6yg0 Commented Jul 8, 2019 at 15:04

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer, but nothing changed.
Which browser and which version are you using?
I've added a link to the browser-support of "Customized built-in elements"
I needed to create a custom element, for example “my-xextarea”, that would inherit from “textarea” and was absolutely the same, with the exception of the tag name. But it turns out that it is impossible to do it the way I wanted. Perhaps with internal content or with a shadow. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.