Search code examples
javascripthtmlcreateelement

Creating custom elements doesn't work - createElement()


I'm trying to keep my project readable for myself, and I'm trying to create new custom HTML elements.

document.createElement("name", {is: "h2"});
document.createElement("avatar", {is: "img"});
document.createElement("description", {is: "p"});

This is how I use them

$(`<avatar class="dropshadow" src="${friend.avatar}">`).appendTo(box);
$(`<name class="name">${friend.name}</name>`).appendTo(box);
$(`<description class="noselect">${friend.description}</description>`).appendTo(box);

Unfortunately, none of these work. They are not treated as their inherited element. When inspecting the nodes, the prototypes are HTMLUnknownElementPrototype, which tells me it doesn't work. What am I doing wrong here? This doesn't make sense.


Solution

  • Well boy aren't I dumb custom elements cannot be created with createElement(), but with customElements.define(), with the limitation being that the tag name must include a hyphen.

    Look here