Search code examples
javascriptshadow-domcustom-element

Extend HTMLSelectElement



Recently, I tried to extends a HTMLSelectElement instead of creating a brand new element, for semantic and accessibility reasons, i.e :
 let customSelect = function () {
  customElements.define(
    "custom-select",
    class CustomSelect extends HTMLSelectElement {
      connectedCallback() {
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = `
      test
      `;
      }
    },
    { extends: "select" }
  );
};

export default customSelect;

It returned the following error : custom-select.js:6 Uncaught DOMException: Failed to execute 'attachShadow' on 'Element': This element does not support attachShadow.

Ok, that was predictable.

Since I can't work with shadow-dom, my question is what is the best solution from there?
So far, I can imagine:

  • Working directly with the innerHTML of this component.
  • Creating that brand new element to work with shadow dom.
  • Overwriting the existing shadow? (If such method could possibly exist).

So what's in your mind is the most simple and 'SEO-friendly' solution?
nb : The solution must be custom-element-based


Solution

  • Working directly with the innerHTML of this component.

    It's the "most simple and 'SEO-friendly' solution".


    Creating that brand new element to work with shadow dom.

    Potentialy the most user-friendly as you can define an enhanced UI.


    Overwriting the existing shadow?

    Not possible. It is read-only.


    Example of <select> enhanced with Custom Elements here in this other SO post.