0

Chrome and Firefox don't visually update svg after adding an element with jQuery :

  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <script src="../js/jquery-3.2.1.min.js"></script>
    </head>
    <body>
      <svg width="300" height="300" viewBox="0 0 300 300" >
      </svg>
      <script>
         jQuery('<circle/>', {
                 r: "25",
                 cx: "80",
                 cy: "80"
              }).appendTo('svg');
      </script>
    </body>
  </html>

Element is visible and editable in devTools but it appears only after inserting a space in the tag.

What do I miss ?

Florimond
  • 47
  • 8

1 Answers1

0

In short, jQuery is made for handling HTML elements and can't deal with svg. See this answer for a more detailed explanation. You need to use plain javascript to manipulate the DOM as demonstrated here:

var svg = document.getElementsByTagName('svg')[0];  //Get the first svg element
var shape = svg.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.setAttributeNS(null, "cx", 80);
shape.setAttributeNS(null, "cy", 80);
shape.setAttributeNS(null, "r",  25);

But a cool alternative that can help with this if you're doing a lot of SVG manipulation is Snap.svg Using Snap.svg you could, instead, create it like this:

var s = Snap("svg");
var circle = s.circle(80, 80, 25);
xr280xr
  • 12,621
  • 7
  • 81
  • 125