2

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> ```


  
1
  • 1
    you need to close the svg tag: </svg> Commented Jul 9, 2020 at 19:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.