Question

I'm trying to append a path element to some inline svg using javascript but I'm getting the error: "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist" Can anyone explain why this javascript is not working with my HTML?

<body>
    <svg height='500' width='500'></svg>


    <script>
        var svg =  document.getElementsByTagName("svg")[0];
        var pathElement = svg.appendChild("path");
    </script>

</body>
Was it helpful?

Solution

appendChild takes an element and not a string so what you need is something like this...

var svg = document.getElementsByTagName("svg")[0];
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");

// Use path.setAttribute("<attr>", "<value>"); to set any attributes you want

var pathElement = svg.appendChild(path);

OTHER TIPS

Working example for anyone passing by who wants to see it in action: http://jsfiddle.net/huvd0fju/

HTML

<svg id="mysvg" width="100" height="100">
   <circle class="c" cx="50" cy="50" r="40" fill="#fc0" />
</svg> 

JS

var mysvg = document.getElementById("mysvg");
//uncomment for example of changing existing svg element attributes
/*
var mycircle = document.getElementsByClassName("c")[0];
mycircle.setAttributeNS(null,"fill","#96f");
*/
var svgns = "http://www.w3.org/2000/svg";
var shape = document.createElementNS(svgns, "rect");
shape.setAttributeNS(null,"width",50);
shape.setAttributeNS(null,"height",80);
shape.setAttributeNS(null,"fill","#f00");
mysvg.appendChild(shape);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top