javascripthtmldialogcustom-element

Extending an HTMLDialogElement throws 'does not exist' error


I should be able to create a custom dialog by generating a class which extends HTMLDialogElement. However, when I do that, the .showModal() method throws a "does not exist" error. I'm obviously missing something here, what is it?

HTML:

<modal-dialog></modal-dialog>

JavaScript:

class ModalDialog extends HTMLDialogElement { constructor() { super(); } }

customElements.define('modal-dialog', ModalDialog, {extends: 'dialog'});

document.querySelector('modal-dialog').showModal();

Solution

  • You are specifying a customized built-in element, and the way you use them in the DOM is different to autonomous custom elements. From MDN documentation on using custom elements:

    Customized built-in elements inherit from basic HTML elements. To create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property). For example <p is="word-count">, or document.createElement("p", { is: "word-count" }).

    So in your example, you need to slightly adjust your usage of the custom element to be like the following:

    class ModalDialog extends HTMLDialogElement { constructor() { super(); } }
    
    customElements.define('modal-dialog', ModalDialog, {extends: 'dialog'});
    
    document.querySelector('dialog').showModal();
    <dialog is="modal-dialog"></dialog>