Add SVG element to existing SVG using DOM

JavascriptHtmlDomSvg

Javascript Problem Overview


I have a HTML construction that resembles the following code:

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

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.

Javascript Solutions


Solution 1 - Javascript

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("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace
newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data
newElement.style.stroke = "#000"; //Set stroke colour
newElement.style.strokeWidth = "5px"; //Set stroke width
svg.appendChild(newElement);

This code will produce something like this:

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



createElement: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

createElementNS: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS

Solution 2 - Javascript

If you're dealing with svg's a lot using JS, I recommend using d3.js. Include it on your page, and do something like this:

d3.select("#svg1").append("circle");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbiggdmanView Question on Stackoverflow
Solution 1 - Javascriptm93aView Answer on Stackoverflow
Solution 2 - Javascriptragingsquirrel3View Answer on Stackoverflow