Search code examples
htmlweb-componentcustom-element

How to use custom elements without hyphen in their name?


I have a XML file and want to insert it into HTML. There is <book> tags in the XML, so I want to define a custom element <book>.

However, it seems that a hypen (-) in the name is required...

I don't want to write tags like <my-book> in the XML file.

Is there a way?


Solution

  • Custom Elements must contain a hyphen.

    But nothing stops you from using <book> notation in your XML and then client-side parse all those unknown tags to something else. But you will get a FOUC

    <my-book-elements>
      <book id="The World according to Garp" />
      <book id="The war of the worlds" />
      <book id="Around the world in eighty days" /> 
      Bye Bye World
    </my-book-elements>
    
    <script>
      customElements.define('my-book-elements', class extends HTMLElement {
        connectedCallback() {
          setTimeout(() => { // make sure we can work with the inner DOM nodes
            this.append(...[...this.querySelectorAll("*")].map(node => {
              let book = document.createElement("my-" + node.localName);
              book.id = node.id;
              //node.remove();// not required, innerHTML will replace everything
              return book;
            }));
          });
        }
      });
      customElements.define("my-book", class extends HTMLElement {
        connectedCallback() {
          this.innerHTML = `<div>${this.id}</div>`;
        }
      });
    </script>