Create an SVG Element from a Text String in JavaScript

November 2025

The Code

This is how I'm making SVGs from text strings.

JavaScript
function makeSVG(input) {
  const tmpl = document.createElement("template");
  tmpl.innerHTML = input;
  const wrapper = tmpl.content.cloneNode(true);
  const svg = wrapper.querySelector("svg");
  return svg;
}

The Example

HTML

<div class="targetElement"></div>

<script>
  const svgText = `<svg version="1.1"
     width="300" 
     height="200"
     xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="red" />
  <circle cx="150" cy="100" r="80" fill="green" />
  <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>`;

  const svgEl = makeSVG(svgText);
  const target = document.querySelector(".targetElement");
  target.appendChild(svgEl);
</script>

Output

SVG

The Notes

The way I'm doing this is a little hacky. There's a more formal way to do it with:

document.createElementNS();

But it's more complicated and takes more steps. I've yet to see any issues doing my way.

- a

end of line

References

Share link:
https://www.alanwsmith.com/en/36/ah/p1/md/?create-an-svg-element-from-a-text-string-in-javascript