Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add svg using javascript?

Tags:

javascript

svg

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.

like image 533
Gorrut Avatar asked Mar 12 '23 09:03

Gorrut


1 Answers

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.

like image 150
Wainage Avatar answered Mar 20 '23 10:03

Wainage