2

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?

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • I do not recognize in your code the normal way of using custom-elements. if that helps, i recently posted a response using custom-elements -> https://stackoverflow.com/questions/60573934/create-options-with-constructor-javascript/60574214#60574214 – Mister Jojo Mar 09 '20 at 21:19

3 Answers3

1

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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

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?

Nick
  • 383
  • 1
  • 4
  • 16
0

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->
Supersharp
  • 29,002
  • 9
  • 92
  • 134