How to create a custom element that contains special characters in its name?

Viewed 419

I have a custom HTML element that was registered in an external library with a name containing special Unicode characters. I would like to dynamically create an element of that kind, so I tried to use document.createElement, but doing so results in a runtime error in Chrome and Firefox because, apparently, the name of the element is not valid. Only Safari allows creating the element in this way.

Here is a simplified example:

// External code
class TestElement extends HTMLElement
{ }
customElements.define("emotion-", TestElement); // OK
console.log("custom element registered");

// My code
document.createElement("emotion-"); // Error in Chrome and Firefox
console.log("custom element created");

Note that the HTML spec itself cites emotion- as an example of a valid custom element name.

How can I create such a custom element in JavaScript?

3 Answers

You can use innerHTML instead document.createElement to create your element in DOM

// External code
class TestElement extends HTMLElement
{ }
customElements.define("emotion-", TestElement); // OK
console.log("custom element registered");

// My code
box.innerHTML = "<emotion- class='el'></emotion->"
console.log("custom element created");
.el { border: 1px solid red }
<div id=box></div>

Make sure that you are using:

<meta charset="UTF-8">

Or try to use this solution:

function emojiUnicode (emoji) {
    var comp;
    if (emoji.length === 1) {
        comp = emoji.charCodeAt(0);
    }
    comp = (
        (emoji.charCodeAt(0) - 0xD800) * 0x400
      + (emoji.charCodeAt(1) - 0xDC00) + 0x10000
    );
    if (comp < 0) {
        comp = emoji.charCodeAt(0);
    }
    return comp.toString("16");
};
emojiUnicode(""); # result "1f600"

Thanks to How to convert one emoji character to Unicode codepoint number in JavaScript?

To complete other answer you'd rather use new with the class name to create the custom element:

document.body.appendChild( new TestElement )

See the example below:

class TestElement extends HTMLElement {
  constructor() {
    super()
    console.log( 'emotion- created' )
    this.attachShadow( { mode: 'open' } ).innerHTML = 'Hello '
  }
}
customElements.define( 'emotion-', TestElement )

var elem = new TestElement
elem.classList.add( 'el' )
document.body.appendChild( elem )
.el { color: red }
<emotion-></emotion->

Related