To add an SVG element to an existing SVG using DOM with JavaScript, we use the createElementNS
method.
For instance, we write
const [svg] = document.getElementsByTagName("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);
to get the svg element with getElementsByTagName
.
And then we call createElementNS
to create a path element in the "http://www.w3.org/2000/svg"
namespace.
Next, we add the d
attribute to the path element with setAttribute
.
And then we set the stroke
and strokeWidth
styles on the path element.
Finally, we call svg.appendChild
to append newElement
to the svg element.