Francisco
Francisco

Reputation: 31

Dynamically adding elements to loaded svg file

After loading an svg file from InkScape I want to add new elements to the drawing, created under program control. This seems to work fine if we just change the attributes of already present elements, but new created ones, even if they appear when inspecting the DOM, do not show!

A hand-simplified SVG test file:

<svg id="svg8" width="1e3" height="750" version="1.1" 
 viewBox="0 0 264.58333 198.43751" xmlns="http://www.w3.org/2000/svg">

    <g id="layer"><circle id="cc0" cx="20" cy="20" r="10"/></g>

</svg>

The javascript/html file:

<!doctype html><html><head><meta charset="UTF-8"/>

<script>
    function addCircle() {
        var svgDoc = document.getElementById("test");
        var svg = svgDoc.contentDocument;
        var svgns = svgDoc.namespaceURI;

        // Ok, this changes the circle to red
        var c0 = svg.getElementById("cc0");
        c0.setAttribute("fill", "#ff0000");

        var layer = svg.getElementById("layer");

        // Create a circle inside layer "g"
        var cc = document.createElementNS(svgns, "circle");
        cc.setAttribute("cx", "50");
        cc.setAttribute("cy", "50");
        cc.setAttribute("r", "20");

        layer.appendChild(cc);
        // However it's not updating the screen
        // even if DOM shows the circle is there, inside the "g"
    }
</script></head>

<body>
<object id="test" data="test.svg" type="image/svg+xml"></object>
<script>    
    document.onreadystatechange = function(){
       if(document.readyState === 'complete') addCircle(); }
</script>
</body>
</html>

What am I doing wrong? Or what am I missing? Thank you!

Upvotes: 0

Views: 1455

Answers (2)

Kaiido
Kaiido

Reputation: 136618

You are getting the namespaceURI of the <object> element.
What you need is the one of the inner document's documentElement :

function addCircle() {
  // this is the <object>
  var svgDoc = document.getElementById("test");
  var svg = svgDoc.contentDocument;
  // here get the real svg document
  var svgns = svg.documentElement.namespaceURI;
  //...

As a plunker since stacksnippets® won't allow the modification of inner frames...

Upvotes: 0

Jibin.Jay
Jibin.Jay

Reputation: 342

Its the issue with your svg namespace that you are passing to create the circle. Try this

var cc = document.createElementNS("http://www.w3.org/2000/svg", "circle");

Upvotes: 2

Related Questions