quentinkrammer
quentinkrammer

Reputation: 62

Create SVG Element from String and append it to Div Element

I want to create SVG Elements from a String like

var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

And then append it to an existing HTML Element using JavaScript. Been Trying a lot of stuff but I seem to have gotten stuck with this error: https://i.sstatic.net/0XUXF.png

I tried this one as well, but didn't get it to work: https://jsfiddle.net/ramnathv/rkkpfvfz/

I wouldn't mind at all if you could explain it in a way a six year old could understand it ^^

THX a lot for any help!

<html>
<body>

<h2>Boolean Network</h2>

<button type="button" onclick="appendSVG1()">Next</button>
<button type="button" onclick="appendSVG2('svgAnchor', svgStr)">Next2</button>

<div id="svgAnchor" value="3">

</div>

<script>
var parser = new DOMParser();
var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

function appendSVG1(){
    anchor = document.getElementById("svgAnchor");
    //nextState = parseInt(anchor.getAttribute("value")) + 1;
    //anchor.setAttribute("value", nextState);
    newSVG = parser.parseFromString(svgStr, "image/svg+xml");
    anchor.appendChild(document.adoptNode(newSVG.documentElement));
}

function appendSVG2(id, xml_string){
  var doc = new DOMParser().parseFromString(xml_string, 'application/xml');
  var el = document.getElementById(id)
  el.appendChild(el.ownerDocument.importNode(doc.documentElement, true))
}

</script> 
</body>
</html> ```


  

Upvotes: 2

Views: 2447

Answers (1)

Brilliand
Brilliand

Reputation: 13714

I don't know how to make the method you've been trying work, but there's a much simpler way: put everything in innerHTML and let the browser sort out the details.

<html>
    <body>

    <h2>Boolean Network</h2>

    <button type="button" onclick="appendSVG('svgAnchor', svgStr)">Next</button>

    <div id="svgAnchor" value="3">

    </div>

    <script>
    var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';

    function appendSVG(id, xml_string){
      var el = document.getElementById(id)
      el.innerHTML = xml_string;
    }

    </script> 
    </body>
    </html>

As enxaneta pointed out, you're missing the </svg> closing tag, which might have been your original problem. innerHTML puts the browser in full "automatically fix errors" mode, so simple mistakes like missing a closing tag get silently repaired.

Upvotes: 2

Related Questions