biggdman biggdman - 8 months ago 73
HTML Question

Add SVG element to existing SVG using DOM

I have a HTML construction that resembles the following code:

<div id='intro'>
//draw some svg elements

I want to be able to add some elements to the SVG defined above using javascript and DOM. How would I accomplish that? I was thinking of

var svg1=document.getElementById('intro').getElementsByTagName('svg');
svg1[0].appendChild(element);//element like <line>, <circle>

I am not very familiar with using DOM, or how to create the element to be passed to appendChild so please help me out with this or perhaps show me what other alternatives I have to solve this issue. Thanks a lot.


If you want to create an HTML element, use document.createElement function. SVG uses namespace, that's why you have to use document.createElementNS function.

var svg = document.getElementsByTagName('svg')[0]; //Get svg element
var newElement = document.createElementNS("", 'path'); //Create a path in SVG's namespace
newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data = "#000"; //Set stroke colour = "5px"; //Set stroke width

This code will produce something like this:

 <path d="M 0 0 L 10 10" style="stroke: #000; stroke-width: 5px;" />