Add SVG element to existing SVG using DOM

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

Leave a Comment