Search code examples
javascriptsvgappendchild

Append a path to SVG with javascript


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>

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);