Satoru Kikuchi
Satoru Kikuchi

Reputation: 1189

How to create Material Icon with Pure JavaScript

I'm thinking about how to create Material Icon with pure JavaScript(document.createElement)

const iconBox = document.createElement("div");
iconBox.style.width = "28px";
iconBox.style.cursor = "pointer";
iconBox.style.display = "flex";
iconBox.style.opacity = "1";
iconBox.style.position = "relative";
iconBox.style.alignItems = "center";
iconBox.style.justifyContent = "center";
iconBox.style.backgroundColor = "#ffffff";

const svg = document.createElement("svg");
svg.style.width = "1em";
svg.style.height = "1em";
svg.style.flexShrink = "inlineBlock";
svg.style.transition = "fill 200ms";
svg.style.flexShrink = "0";
svg.style.userSelect = "none";
svg.style.fontSize = "2.1875rem";

const path = document.createElement("path");
path.setAttribute(
  "d",
  "M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"
);
svg.appendChild(path);
iconBox.appendChild(svg);

const container = document.getElementById("container");
container!.appendChild(iconBox);
console.log(container, "container");

But somehow, in a web browser, the icon doesn't show up(The div, svg, and path are there)

This is a screenshot of a web browser console.

enter image description here

This is my codesandbox, the whole code is there.

Upvotes: 2

Views: 371

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 80986

Because svg elements are XML rather than HTML, the elements need to be created with the appropriate namespace. So instead of

document.createElement("svg");

and

document.createElement("path");

you need to use:

document.createElementNS("http://www.w3.org/2000/svg", "svg");

and

document.createElementNS("http://www.w3.org/2000/svg", "path");

Edit Pure Typescript

Related answer containing further explanation:

Documentation on createElementNS:

Upvotes: 2

Related Questions