1

I am creating an SVG element dynamically and appending it to another element in the page. The page displays the SVG element that is part of the HTML DOM written in the file, but it does not display the dynamically created one from Javascript.

I examined the rendered HTML output and found no difference between the dynamically created SVG and the one specified in the HTML file.

var out = document.getElementById("output");
var svg = document.createElement("svg");
svg.setAttribute("width",50);
svg.setAttribute("height",50);
svg.setAttribute("style","background-color:#bada55");
svg.innerHTML = "why is this not displayed as SVG?";
out.appendChild(svg);
<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
</div>

What am I doing wrong?

Edit:

PS: I am using Chrome, and the way I see the output is: The beige SVG is rendered correctly, with no text inside it. The green SVG (dynamically created) appears as if it was a <span> with the text appearing inside it.

Here is an image of what I see: Here is the expected output and what I am currently seeing

And here is the rendered HTML:

<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
  <svg width="50" height="50" style="background-color:#bada55">why is this not displayed as SVG?</svg>
</div>
Ahmad
  • 12,336
  • 6
  • 48
  • 88

1 Answers1

2

use createElementNS and that will solve your problem.

var out = document.getElementById("output");
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'background-color:#bada55');
svg.setAttribute('width', '50');
svg.setAttribute('height', '50');
svg.innerHTML = "why is this not displayed as SVG?";
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

out.appendChild(svg);
<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
</div>
Narendra
  • 4,514
  • 2
  • 21
  • 38