How to add an SVG element to an existing SVG using DOM with JavaScript?

To add an SVG element to an existing SVG using the Document Object Model (DOM) with JavaScript, we can create the SVG element you want to add.

Then we set any attributes or properties of the new SVG element.

And we append the new SVG element to the existing SVG container.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add SVG Element using DOM with JavaScript</title>
</head>
<body>

<!-- Existing SVG container -->
<svg id="existing-svg" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" fill="red" />
</svg>

<script>
  // Create a new SVG circle element
  const newCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");

  // Set attributes for the new circle
  newCircle.setAttribute("cx", "50");
  newCircle.setAttribute("cy", "50");
  newCircle.setAttribute("r", "25");
  newCircle.setAttribute("fill", "blue");

  // Get the existing SVG container
  const svgContainer = document.getElementById("existing-svg");

  // Append the new circle to the existing SVG container
  svgContainer.appendChild(newCircle);
</script>

</body>
</html>

We create a new SVG circle element using document.createElementNS() method, specifying the namespace URI for SVG elements.

Next we set attributes for the new circle using setAttribute() method.

Then we get the existing SVG container using getElementById() method.

Finally we append the new circle to the existing SVG container using appendChild() method.

This way, we can dynamically add SVG elements to an existing SVG using JavaScript and the DOM. Adjust the attributes and properties as needed for your specific use case.