To add SVG elements to existing SVG using DOM manipulation and JavaScript, we can select the svg
element.
Then we can create an element with a namespace and put it inside the svg
element as its child.
For instance, if we have the following HTML:
<svg></svg>
Then we can select the element and add a path
element into it by writing:
const svg = document.querySelector('svg');
const newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path');
newElement.setAttribute("d", "M 0 0 L 10 10");
newElement.style.stroke = "#000";
newElement.style.strokeWidth = "5px";
svg.appendChild(newElement);
We call document.querySelector
to get the svg
element.
Then we call document.createElementNS
to create a new path
element with a namespace.
Next, we call newElement.setAttribute
to add the d
attribute to add the path code for the SVG.
Next, we set the stroke
property to set the stroke color.
And then we set the strokeWidth
property to set the stroke width.
Finally, we call appendChild
with newElement
to append it as the svg
element’s child.
Now we should see a short diagonal line displayed on the screen.