4

I am using this code to insert svg into a div tag.

var container = document.getElementById("div_id");
var svg = document.createElement("svg");
svg.setAttribute("width",container.clientWidth);
svg.setAttribute("height",container.clientHeight);    
container.appendChild(svg);

On checking using the developer tools in the browser, svg is present inside the div. But when I hover over the svg in the developer tools, it is showing "svg 0*0" i.e eventhough the width and height attributes are set as 500 and 400 I cannot view it in the page. I tried to insert a line into the svg, which again can be seen inside svg, but not visible in the browser. Need help.

Gorrut
  • 268
  • 4
  • 10
  • 1
    [Your code appears to work just fine.](https://jsfiddle.net/uf822snd/) (Using Firefox.) – Pointy May 06 '16 at 18:42
  • Possible duplicate of [How can I force WebKit to redraw/repaint to propagate style changes?](http://stackoverflow.com/questions/3485365/how-can-i-force-webkit-to-redraw-repaint-to-propagate-style-changes) – Sumurai8 May 06 '16 at 18:57

1 Answers1

7

Use

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

to create your SVG. Use it for elements as well.

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

The work just like regular elements.

Wainage
  • 4,892
  • 3
  • 12
  • 22
  • The link you provided don't cover the issue specifically (it's hidden in there) and it's not obvious how to search or ask for this info. Hardly worth a down vote when I'm sure my 30 seconds taught him something. – Wainage May 06 '16 at 19:26
  • @Wainage Do I have to use 'createElementNS' for every element that needs to be created, or should I use it only for the '' and 'createElement' for the elements inside it. – Gorrut May 06 '16 at 19:51
  • @KarthikManivasgam All your SVG elements (path, circle, rect ...) need createElementsNS – Wainage May 06 '16 at 19:52
  • I will make your reply as the answer. And friends if you have alternate solutions, you are always welcome – Gorrut May 06 '16 at 19:59